Objects
A structure for grouping related data and functionality together.
Object literals
const student = {
// Properties
id: 1,
name: "Suzuki",
age: 20,
// Method shorthand (ES6)
introduce() {
return `My name is ${this.name}, and I am ${this.age} years old.`;
}
};
// Accessing properties
console.log(student.name); // Suzuki
console.log(student["age"]); // 20
// Calling a method
console.log(student.introduce()); // My name is Suzuki, and I am 20 years old.
Shorthand property names and computed property names
const name = "Yamada";
const age = 30;
// If the variable name and property name are the same, you can shorten it (shorthand)
const user = { name, age };
console.log(user); // { name: 'Yamada', age: 30 }
// Wrapping in [ ] lets you decide the key dynamically (computed property name)
const key = "score";
const result = { [key]: 100 };
console.log(result); // { score: 100 }
Object destructuring (ES6)
You can extract the properties you need from an object and assign them to variables.
const student = { name: "Suzuki", age: 20 };
const { name, age } = student;
console.log(name); // Suzuki
console.log(age); // 20
The spread syntax (ES2018)
// Copying and merging objects
const person = { name: "Yamada", age: 35 };
const job = { position: "Engineer", years: 5 };
// Create a new object
const employeeInfo = { ...person, ...job };
console.log(employeeInfo);
// { name: 'Yamada', age: 35, position: 'Engineer', years: 5 }
Object manipulation methods
const user = { id: 101, username: "user1", email: "user1@example.com" };
// Get the object's keys as an array
console.log(Object.keys(user)); // ['id', 'username', 'email']
// Get the object's values as an array
console.log(Object.values(user)); // [101, 'user1', 'user1@example.com']
// Get the key-value pairs as an array
console.log(Object.entries(user));
// [['id', 101], ['username', 'user1'], ['email', 'user1@example.com']]
Safe access to nested values
When you access a deep level of an object, it errors if a property along the way doesn't exist. Using optional chaining ?. (ES2020), you can access it safely.
const user = {
name: "Suzuki",
address: { city: "Tokyo" }
};
// Without ?.: it errors if something in the middle is undefined
// console.log(user.company.name); // ❌ TypeError
// With ?.: it returns undefined if something in the middle is missing (no error)
console.log(user.company?.name); // undefined
console.log(user.address?.city); // Tokyo
// Combine with ?? to specify a default value
const city = user.address?.city ?? "Not set";
console.log(city); // Tokyo
Beginner-friendly explanation
?. is an operator that "stops there and returns undefined if the left side is null or undefined." user.company?.name means "the name if company exists, otherwise undefined," which prevents errors when accessing deep levels.
What to read next
- Arrays — Handle data lined up in order