Objects & Key-Value Pairs
Quick Overview
Object keys are always strings, so `obj[1]` and `obj["1"]` reach the same slot. `?.` stops a lookup at the first `null` or `undefined` rather than throwing on the property after it.
Deep Dive
1. Key-Value Records
An object is an unordered collection of related data stored as key: value property pairs enclosed in curly braces {...}.
2. Why It Matters
Objects model real-world entities (users, products, configurations) in application state.
3. Dot Notation vs. Bracket Notation
Access object properties using dot notation (user.name) or bracket notation (user["name"]) when keys contain spaces or are stored in dynamic variables:
const user = {
name: "Sarah",
role: "Developer",
"active status": true,
};
// Dot notation
console.log(user.name); // "Sarah"
// Bracket notation (Required for spaces or dynamic variables)
console.log(user["active status"]); // true
const keyToRead = "role";
console.log(user[keyToRead]); // "Developer"
// Updating & Adding Properties
user.role = "Lead Developer";
user.location = "San Francisco";
4. Safe Property Navigation (Optional Chaining ?.)
Reading a property from a non-existent object (e.g. null.profile) throws an uncaught TypeError: Cannot read properties of null. Use optional chaining (?.) to safely return undefined instead of crashing:
const userProfile = { name: "Alex" };
// Safe optional chaining
console.log(userProfile.address?.city); // undefined (No crash!)
5. Common Mistakes
- Using Dot Notation with Dynamic Variables: Writing
user.keyToReadsearches for a property literally named"keyToRead". Use bracket notationuser[keyToRead]when reading dynamic variable keys! - Comparing Objects with ===: Objects are compared by memory reference, NOT by content! Two identical objects
{ a: 1 } === { a: 1 }evaluates tofalsebecause they occupy different memory addresses.
6. Try It Yourself
Write it yourself. The tests below run against your code.
Safely Get User Email Property
Examples
7. Next Steps
Objects structure entity data. Next, let's explore functional array transformations starting with .map()!
Next Up in JavaScript Engine & Core Language
Data Types in JavaScript: Primitives vs. Objects
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
Variables: const, let & var (The Box Metaphor)
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Strings & Template Literals `${}`
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.