Home
← All questions

Different ways to create objects in JavaScript

EasyPremiumJavaScript

JavaScript interview practice: Enumerate object creation patterns and Object.create vs Object.assign.

Answer

// 1. Object literal
const a = { x: 1 };

// 2. Constructor function
function Point(x) { this.x = x; }
const b = new Point(1);

// 3. ES6 class
class P { constructor(x) { this.x = x; } }
const c = new P(1);

// 4. Object.create (set prototype explicitly)
const proto = { greet() { return "hi"; } };
const d = Object.create(proto);

// 5. Factory function
const makePoint = (x) => ({ x });
const e = makePoint(1);

// 6. Object.assign (merge/clone shallow)
const f = Object.assign({}, a, { y: 2 });
  • Object.create(proto) creates a new object with proto as its prototype (no own props).
  • Object.assign(target, ...sources) copies own enumerable properties (shallow) onto target.
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium