Objects
JavaScript's key-value store — creating, accessing, modifying, and the methods for working with object data.
Objects do remember the order you added properties, except for keys that look like whole numbers. Those ("4", "30", real numbers too) always come first, in ascending numeric order, before any other keys. So a queue or a menu keyed by IDs comes back out of Object.keys, for...in or JSON.stringify in a different order than you put it in.
const queue = {}; // jobs added in priority order
queue["urgent"] = "restart server";
queue["30"] = "rotate logs";
queue["4"] = "send report";
console.log(Object.keys(queue)); // [ '4', '30', 'urgent' ]Storing named information in objects
Arrays are great for ordered lists. But what about a person? A person has a name, an age, an email address — information that belongs together but doesn't have a natural order. That's what an object is for: a collection of named values.
Creating an object
// Curly braces, key: value pairs, commas between them
const user = {
name: "Alice",
age: 30,
email: "alice@example.com",
isActive: true
};
// The keys are the names. The values are the data.
// Keys don't need quotes unless they contain spaces or special characters.Accessing properties — two ways
const user = { name: "Alice", age: 30 };
// Dot notation — use this most of the time
console.log(user.name); // "Alice"
console.log(user.age); // 30
// Bracket notation — use when the key is in a variable, or has spaces
const key = "name";
console.log(user[key]); // "Alice" — key comes from a variable
const weirdObj = { "first name": "Bob" };
console.log(weirdObj["first name"]); // "Bob" — spaces need bracketsAdding, updating, and deleting properties
const profile = { name: "Alice" };
profile.age = 30; // add a new property
profile.name = "Alice Smith"; // update an existing property
delete profile.age; // remove a property
console.log(profile); // { name: "Alice Smith" }Checking if a property exists
const user = { name: "Alice", age: 30 };
"name" in user // true
"email" in user // false
user.email !== undefined // false (same idea, less reliable)
// Safe access with optional chaining:
console.log(user?.address?.city); // undefined (no error)Object.keys, Object.values, Object.entries
The three methods for iterating over an object's data:
const scores = { alice: 95, bob: 87, charlie: 72 };
Object.keys(scores) // ["alice", "bob", "charlie"] — just the keys
Object.values(scores) // [95, 87, 72] — just the values
Object.entries(scores) // [["alice",95],["bob",87],["charlie",72]] — pairs
// Loop over key-value pairs:
for (const [name, score] of Object.entries(scores)) {
console.log(`${name}: ${score}`);
}
// alice: 95
// bob: 87
// charlie: 72Object.keys, values and entries above all follow the same rule: integer-like keys in ascending order first, then the remaining string keys in insertion order. When order matters and keys may be numeric, use a Map (which keeps insertion order for every key) or an array:
const queue = new Map(); // a Map keeps insertion order for every key
queue.set("urgent", "restart server");
queue.set("30", "rotate logs");
queue.set("4", "send report");
console.log([...queue.keys()]); // [ 'urgent', '30', '4' ]Destructuring — unpack values into variables
const user = { name: "Alice", age: 30, city: "Mumbai" };
// Unpack specific properties:
const { name, city } = user;
console.log(name); // "Alice"
console.log(city); // "Mumbai"
// Rename while destructuring:
const { name: userName, age: userAge } = user;
console.log(userName); // "Alice"
// Default values (used if property doesn't exist):
const { country = "India" } = user;
console.log(country); // "India" — user has no country, default used
// In function parameters — very common pattern:
function greet({ name, city }) {
console.log(`${name} lives in ${city}`);
}
greet(user); // "Alice lives in Mumbai"Spread — copy or merge objects
const defaults = { theme: "dark", lang: "en", fontSize: 14 };
const userPrefs = { lang: "hi", fontSize: 16 };
// Merge: later properties win over earlier ones
const settings = { ...defaults, ...userPrefs };
console.log(settings);
// { theme: "dark", lang: "hi", fontSize: 16 }
// Shallow copy:
const copy = { ...defaults };
copy.theme = "light";
console.log(defaults.theme); // "dark" — original unaffectedMethods — functions inside an object
const counter = {
count: 0,
// Method shorthand (modern syntax):
increment() {
this.count += 1; // 'this' refers to the counter object
},
reset() {
this.count = 0;
},
value() {
return this.count;
}
};
counter.increment();
counter.increment();
counter.increment();
console.log(counter.value()); // 3
counter.reset();
console.log(counter.value()); // 0Official Sources
- MDN Web Docs — Working with objects
- MDN Web Docs — Object
- MDN Web Docs — JSON
- ECMAScript 2024 — Property Descriptors (§10.1)
The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.