Skip to main content

Ways to declare an object

JavaScript has several ways to create an object, and the choice depends on what you need: a plain object, a copy, a template, or a class instance.

Here are all the main options:


1. Object literal - the simplest and most common way

javascript
const user = { name: 'Tim', age: 25 };

Creates a new object right away with the needed properties. This is the most common way in real code.


2. Via the Object constructor

javascript
const user = new Object(); user.name = 'Tim'; user.age = 25;

Works, but is usually not recommended, since literals ({}) are shorter and clearer.


3. Via Object.create(proto)

javascript
const person = { species: 'human' }; const user = Object.create(person); user.name = 'Tim'; console.log(user.species); // "human" (inherited from person)

Lets you create an object with a specific prototype - often used in advanced scenarios (for example, when working with prototypes manually).


4. Via a constructor function

javascript
function User(name, age) { this.name = name; this.age = age; } const tim = new User('Tim', 25); console.log(tim.name); // "Tim"

Constructor functions (with new) create objects of a specific "type" and automatically set this to the new object.


5. Via a class (class)

javascript
class User { constructor(name, age) { this.name = name; this.age = age; } } const tim = new User('Tim', 25); console.log(tim.name); // "Tim"

Syntactic sugar over a constructor function, used in modern JS to create instances.


6. Via destructuring and spread

javascript
const base = { role: 'user' }; const user = { ...base, name: 'Tim', age: 25 };

Creates a copy of an existing object with new properties added.


7. Via Object.fromEntries()

javascript
const entries = [['name', 'Tim'], ['age', 25]]; const user = Object.fromEntries(entries); console.log(user); // { name: 'Tim', age: 25 }

Useful when you need to create an object from key-value pairs (for example, after Object.entries() or Map).


Summary

WayExampleWhen to use
Literal {}{ name: 'Tim' }the most common way
new Object()new Object()rarely, for compatibility
Object.create(proto)Object.create(person)needs prototype control
Constructor functionnew User()an old but working approach
classnew User()a modern, OOP approach
Spread / copy{ ...obj }duplicating and extending objects
Object.fromEntries()Object.fromEntries(pairs)creating from key-value pairs

In one phrase:

In JS, an object can be created in many ways - from a plain {} to class, but in 95% of cases a literal {} or class is enough for structured data.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.