Creating Objects
const person = {
name: "Alice",
age: 25,
greet() {
return `Hi, I am ${this.name}`;
}
};
console.log(person.name); // Alice
console.log(person["age"]); // 25
console.log(person.greet()); // Hi, I am Alice
Destructuring
const { name, age } = person;
console.log(name); // Alice
// With rename
const { name: fullName } = person;
// Default values
const { city = "Unknown" } = person;
Spread with Objects
const defaults = { color: "blue", size: "M" };
const custom = { size: "L", weight: "light" };
const merged = { ...defaults, ...custom };
// { color: "blue", size: "L", weight: "light" }
Classes (ES6+)
class Animal {
constructor(name, sound) {
this.name = name;
this.sound = sound;
}
speak() {
return `${this.name} says ${this.sound}!`;
}
}
class Dog extends Animal {
constructor(name) {
super(name, "woof");
}
fetch() { return `${this.name} fetches the ball!`; }
}
const rex = new Dog("Rex");
console.log(rex.speak()); // Rex says woof!