JavaScript Objects
I. What is a JavaScript Object?
An object is a collection of key-value pairs. Each key is a string (or Symbol), and each value can be any data type: a number, string, array, function, or even another object.
const car = {
color: 'blue',
brand: 'Honda',
};
II. Access properties
You can read, add, or overwrite a property using dot notation or bracket notation.
const person = {
name: "Anna",
age: 22,
hobbies: ["movies", "travel", "art"],
address: {
street: "12 Anderson",
city: "Copenhagen",
country: "Denmark",
},
};
console.log(person.name); // Anna
console.log(person.hobbies[2]); // art
console.log(person.address.country); // Denmark
Use bracket notation when the key is dynamic or contains spaces or special characters:
const key = "name";
console.log(person[key]); // Anna
III. Destructuring
Destructuring extracts values from an object into variables in a single line.
const { name, age } = person;
console.log(name); // Anna
console.log(age); // 22
// Nested destructuring
const { address: { country } } = person;
console.log(country); // Denmark
IV. Add or update properties
Assign to a new key to add it; assign to an existing key to overwrite it.
person.email = "anna@gmail.com"; // add
person.age = 23; // update
V. Methods
An object can hold functions as values. Inside a method, this refers to the object.
const person = {
firstName: "Anna",
lastName: "Smith",
getFullName() {
return `${this.firstName} ${this.lastName}`;
},
};
console.log(person.getFullName()); // Anna Smith
VI. ES6 shorthand properties
When a variable name matches the key you want, you can use the shorthand:
const name = "Anna";
const age = 22;
const person = { name, age };
// same as { name: name, age: age }
VII. Spread operator
Use ... to copy or merge objects:
const defaults = { theme: "light", lang: "en" };
const userSettings = { lang: "fr", fontSize: 14 };
const settings = { ...defaults, ...userSettings };
// { theme: "light", lang: "fr", fontSize: 14 }
Later keys overwrite earlier ones.
VIII. Object.entries, Object.keys, Object.values
These three methods let you iterate over an object’s properties.
const scores = { alice: 90, bob: 85, carol: 92 };
Object.keys(scores); // ["alice", "bob", "carol"]
Object.values(scores); // [90, 85, 92]
Object.entries(scores); // [["alice", 90], ["bob", 85], ["carol", 92]]
// Common pattern: loop with Object.entries
for (const [name, score] of Object.entries(scores)) {
console.log(`${name}: ${score}`);
}
IX. Array of objects
Arrays frequently store objects. Access individual properties with dot notation after indexing.
const food = [
{ id: 1, name: "Chicken curry", origin: "India" },
{ id: 2, name: "Pho", origin: "Vietnam" },
{ id: 3, name: "Kimbap", origin: "Korea" },
];
console.log(food[1].name); // Pho
// Find by property value
const pho = food.find(item => item.name === "Pho");
X. JSON
JSON (JavaScript Object Notation) is the format most APIs use to send and receive data. Convert an object to JSON with JSON.stringify() and parse a JSON string with JSON.parse().
const json = JSON.stringify(food);
// '[{"id":1,"name":"Chicken curry",...}]'
const parsed = JSON.parse(json);
console.log(parsed[0].name); // Chicken curry
XI. Creating multiple objects
When you need many objects with the same shape, use a constructor function (pre-ES6) or a class (modern).
// Modern approach
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const anna = new Person("Anna", 22);
const joe = new Person("Joe", 30);