Objects
Objects
Section titled “Objects”What it means
Section titled “What it means”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).
Examples
Section titled “Examples”// Creating objectsconst user = { name: "Alice", age: 25, email: "alice@example.com", greet() { return `Hello, I'm ${this.name}`; }};
// Accessing propertiesconsole.log(user.name); // dot notationconsole.log(user["email"]); // bracket notation
// Adding/modifying propertiesuser.city = "NYC";user.age = 26;
// Deleting propertiesdelete user.email;
// Computed property namesconst key = "role";const admin = { [key]: "administrator", [`is${key}`]: true};
// Object methodsconst keys = Object.keys(user); // ['name', 'age', 'city', 'greet']const values = Object.values(user); // ['Alice', 26, 'NYC', [Function]]const entries = Object.entries(user); // [['name', 'Alice'], ...]
// Destructuringconst { name, age } = user;console.log(name); // "Alice"
// Spread operatorconst updated = { ...user, verified: true };
// Object.assign (merge objects)const merged = Object.assign({}, user, { premium: true });Common mistake
Section titled “Common mistake”Forgetting that objects are passed by reference:
// BAD - both variables point to same objectconst obj1 = { count: 1 };const obj2 = obj1;obj2.count = 2;console.log(obj1.count); // 2 (unexpected!)
// GOOD - create a copyconst 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.
Quick practice
Section titled “Quick practice”-
How do you check if an object has a property?
Answer
`'key' in obj` or `obj.hasOwnProperty('key')` -
What’s the difference between
Object.keys()andObject.values()?Answer
`Object.keys()` returns array of property names; `Object.values()` returns array of values. -
Extract
nameandagefromconst user = { name: "Bob", age: 30, city: "LA" }using destructuring.Answer
`const { name, age } = user;`