Skip to content

Objects

Objects are collections of key-value pairs. They’re the foundation of JavaScript’s object-oriented features. Keys are strings (or symbols), values can be any type including functions (methods).

// Creating objects
const user = {
name: "Alice",
age: 25,
email: "alice@example.com",
greet() {
return `Hello, I'm ${this.name}`;
}
};
// Accessing properties
console.log(user.name); // dot notation
console.log(user["email"]); // bracket notation
// Adding/modifying properties
user.city = "NYC";
user.age = 26;
// Deleting properties
delete user.email;
// Computed property names
const key = "role";
const admin = {
[key]: "administrator",
[`is${key}`]: true
};
// Object methods
const keys = Object.keys(user); // ['name', 'age', 'city', 'greet']
const values = Object.values(user); // ['Alice', 26, 'NYC', [Function]]
const entries = Object.entries(user); // [['name', 'Alice'], ...]
// Destructuring
const { name, age } = user;
console.log(name); // "Alice"
// Spread operator
const updated = { ...user, verified: true };
// Object.assign (merge objects)
const merged = Object.assign({}, user, { premium: true });

Forgetting that objects are passed by reference:

// BAD - both variables point to same object
const obj1 = { count: 1 };
const obj2 = obj1;
obj2.count = 2;
console.log(obj1.count); // 2 (unexpected!)
// GOOD - create a copy
const obj3 = { count: 1 };
const obj4 = { ...obj3 };
obj4.count = 2;
console.log(obj3.count); // 1 (independent)

Fix: Use spread operator {...obj} or Object.assign({}, obj) to create copies.

  1. How do you check if an object has a property?

    Answer`'key' in obj` or `obj.hasOwnProperty('key')`
  2. What’s the difference between Object.keys() and Object.values()?

    Answer`Object.keys()` returns array of property names; `Object.values()` returns array of values.
  3. Extract name and age from const user = { name: "Bob", age: 30, city: "LA" } using destructuring.

    Answer`const { name, age } = user;`