Object Literals
Objects store key-value pairs. Create them with curly braces.
const person = {
name: "Alice",
age: 30,
job: "Engineer"
};
console.log(person.name); // Alice
console.log(person["age"]); // 30
Try it Yourself โ
Adding and Updating Properties
Assign new values using dot or bracket notation.
const car = { brand: "Toyota" };
car.model = "Camry";
car["year"] = 2022;
car.brand = "Honda";
console.log(car);
// { brand: "Honda", model: "Camry", year: 2022 }
Try it Yourself โ
Deleting Properties
The delete operator removes a property from an object.
const user = { id: 1, name: "Bob", password: "secret" };
delete user.password;
console.log(user);
// { id: 1, name: "Bob" }
console.log(user.password); // undefined
Try it Yourself โ
Checking Property Existence
Use in operator or hasOwnProperty to check if a property exists.
const book = { title: "1984", author: "Orwell" };
console.log("title" in book); // true
console.log("pages" in book); // false
console.log(book.hasOwnProperty("author")); // true
Try it Yourself โ
Object Methods
Objects can hold functions as methods, which can access the object via this.
const calculator = {
value: 0,
add(n) {
this.value += n;
return this;
},
subtract(n) {
this.value -= n;
return this;
},
getResult() {
return this.value;
}
};
calculator.add(10).subtract(3);
console.log(calculator.getResult()); // 7
Try it Yourself โ
Object.keys, values, entries
Static methods return arrays of an object's keys, values, or key-value pairs.
const scores = { math: 90, science: 85, english: 92 };
console.log(Object.keys(scores)); // ["math", "science", "english"]
console.log(Object.values(scores)); // [90, 85, 92]
console.log(Object.entries(scores));
// [["math", 90], ["science", 85], ["english", 92]]
Try it Yourself โ
Constructor Functions
Constructor functions create multiple objects with the same shape.
function Student(name, grade) {
this.name = name;
this.grade = grade;
this.describe = function() {
return this.name + " is in grade " + this.grade;
};
}
const s1 = new Student("Alice", 10);
const s2 = new Student("Bob", 12);
console.log(s1.describe()); // Alice is in grade 10
console.log(s2.describe()); // Bob is in grade 12
Try it Yourself โ
Object Destructuring
Destructuring extracts properties into variables with the same name.
const user = { username: "alice99", email: "alice@mail.com", role: "admin" };
const { username, email } = user;
console.log(username); // alice99
console.log(email); // alice@mail.com
const { role, ...rest } = user;
console.log(role); // admin
console.log(rest); // { username: "alice99", email: "alice@mail.com" }
Try it Yourself โ