Creating objects
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.
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:
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:
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:
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:
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: