How to Create an Object in JavaScript
Learn different ways to create objects in JavaScript including literals, constructors, and classes.
Objects are fundamental to JavaScript, used to store collections of key-value pairs.
Method 1: Object Literal (Recommended)
The most common and simplest way:
// Empty object
const emptyObj = {};
// Object with properties
const person = {
name: "Alice",
age: 25,
city: "Paris"
};
console.log(person.name); // Alice
console.log(person["age"]); // 25
Method 2: Object Constructor
Using the Object constructor:
const person = new Object();
person.name = "Alice";
person.age = 25;
console.log(person); // { name: 'Alice', age: 25 }
Method 3: Object.create()
Create an object with a specific prototype:
const personPrototype = {
greet() {
return `Hello, I'm ${this.name}`;
}
};
const alice = Object.create(personPrototype);
alice.name = "Alice";
console.log(alice.greet()); // "Hello, I'm Alice"
Method 4: Constructor Function
Create multiple objects with the same structure:
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
return `Hello, I'm ${this.name}`;
};
}
const alice = new Person("Alice", 25);
const bob = new Person("Bob", 30);
console.log(alice.greet()); // "Hello, I'm Alice"
Method 5: ES6 Classes
Modern syntax for creating objects:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, I'm ${this.name}`;
}
}
const alice = new Person("Alice", 25);
console.log(alice.greet()); // "Hello, I'm Alice"
Shorthand Properties (ES6+)
When variable names match property names:
const name = "Alice";
const age = 25;
// Instead of { name: name, age: age }
const person = { name, age };
console.log(person); // { name: 'Alice', age: 25 }
Computed Property Names
Use expressions as property names:
const key = "name";
const person = {
[key]: "Alice",
["user" + "Age"]: 25
};
console.log(person); // { name: 'Alice', userAge: 25 }
Summary
- Use object literals for simple, one-off objects
- Use classes for creating multiple objects with shared behavior
- Use Object.create() for prototype-based inheritance
- Use shorthand properties for cleaner code