What are the different ways to create objects in JavaScript?
JavaScriptThe short answer
The main ways are: object literals ({}), Object.create(), constructor functions with new, ES6 classes, and factory functions. Each approach has different use cases — object literals for simple objects, classes for instances with shared methods, and factory functions when you want to avoid new.
Object literal
The simplest and most common way:
const user = { name: 'John', age: 30, greet() { console.log(`Hi, I am ${this.name}`); },};Object.create
Creates an object with a specific prototype:
const personProto = { greet() { console.log(`Hi, I am ${this.name}`); },};const john = Object.create(personProto);john.name = 'John';john.greet(); // "Hi, I am John"Constructor function
function Person(name, age) { this.name = name; this.age = age;}Person.prototype.greet = function () { console.log(`Hi, I am ${this.name}`);};const john = new Person('John', 30);ES6 class
Syntactic sugar over constructor functions:
class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`Hi, I am ${this.name}`); }}const john = new Person('John', 30);Factory function
Returns an object without using new:
function createPerson(name, age) { return { name, age, greet() { console.log(`Hi, I am ${name}`); }, };}const john = createPerson('John', 30);Factory functions avoid this and new, making them simpler. They also naturally support private variables through closures.
When to use what
- Object literal — for one-off objects (config, options, data)
- Class — for creating many instances with shared methods
- Factory function — for creating instances without
this/newcomplexity - Object.create — when you need explicit prototype control
Interview Tip
List all five methods with a brief example for each. The most important ones to know are object literals (everyday use) and classes (creating instances). Mentioning factory functions as an alternative to classes shows you know multiple patterns.
Why interviewers ask this
This tests breadth of JavaScript knowledge. Interviewers want to see if you know more than just object literals and classes, and if you understand the relationship between constructor functions and classes (classes are syntax sugar).