Different ways to create objects in JavaScript
In JavaScript, objects are fundamental data structures that store data as members or properties. Objects can contain both simple values (like strings or numbers) as well as functions or other objects.
Today we'll discuss how to create objects, starting from the most common syntaxes to more advanced methods.
1. Creating objects with literal syntax
const car = {
brand: 'Toyota',
model: 'Corolla',
year: 2020,
start() {
console.log(`${this.brand} ${this.model} is starting...`);
}
};
console.log(car.brand); // 'Toyota'
car.start(); // 'Toyota Corolla is starting...'
Advantages of this method:
- Simple and concise
- Most commonly used in practice
- Clear and fast
2. Creating objects with Object.create()
const animal = {
speak() {
console.log(`I'm a ${this.type}`);
}
};
const dog = Object.create(animal);
dog.type = 'dog';
dog.speak(); // I'm a dog
Advantages of this method:
- Helps build prototype chains
- Easy to inherit properties and methods from parent objects
3. Constructor functions
function Car(brand, model, year) {
this.brand = brand;
this.model = model;
this.year = year;
this.start = function() {
console.log(`${this.brand} ${this.model} is starting...`);
};
}
const myCar = new Car('Tesla', 'Model S', 2022);
myCar.start(); // 'Tesla Model S is starting...'
Advantages of this method:
- Easy to create multiple objects with the same structure
- Also used together with class syntax
4. Using class syntax
class Car {
constructor(brand, model, year) {
this.brand = brand;
this.model = model;
this.year = year;
}
start() {
console.log(`${this.brand} ${this.model} is starting...`);
}
}
const myCar = new Car('BMW', 'X5', 2021);
myCar.start(); // 'BMW X5 is starting...'
Advantages of this method:
- More organized code
5. Merging objects with Object.assign()
const person = { name: 'Anna', age: 25 };
const job = { title: 'Developer', company: 'TechCorp' };
const employee = Object.assign({}, person, job);
console.log(employee); // { name: 'Anna', age: 25, title: 'Developer', company: 'TechCorp' }
Advantages of this method:
- Used to merge two or more objects
- Also useful for creating standard objects