Objects
Table of Contents
Objects are how JavaScript organizes related data and behavior together. While arrays store ordered lists, objects store named properties — key-value pairs that let you model real-world things like users, products, or API responses.
Almost everything in JavaScript is an object (or behaves like one), so understanding them deeply is essential.
Creating Objects
The most common way to create an object is with an object literal:
const user = {
name: "Alice",
age: 28,
email: "alice@example.com",
isActive: true
};
console.log(user.name); // "Alice"
console.log(user.age); // 28
Property names (keys) are strings. Values can be any type — strings, numbers, booleans, arrays, other objects, or functions.
Accessing Properties
Two ways to access properties:
const car = {
make: "Toyota",
model: "Camry",
year: 2023,
"fuel type": "hybrid" // keys with spaces need quotes
};
// Dot notation — cleaner, use when you know the key name
console.log(car.make); // "Toyota"
console.log(car.year); // 2023
// Bracket notation — required for dynamic keys or keys with special characters
console.log(car["fuel type"]); // "hybrid"
const prop = "model";
console.log(car[prop]); // "Camry"
Use dot notation by default. Use bracket notation when the key is dynamic (stored in a variable) or contains special characters.
Adding, Updating, and Deleting Properties
Objects are mutable — you can change them after creation:
const profile = {
name: "Bob"
};
// Add new properties
profile.age = 30;
profile.email = "bob@example.com";
// Update existing properties
profile.name = "Robert";
// Delete properties
delete profile.email;
console.log(profile); // { name: "Robert", age: 30 }
Methods
When a function is stored as an object property, it’s called a method:
const calculator = {
result: 0,
add(n) {
this.result += n;
return this;
},
subtract(n) {
this.result -= n;
return this;
},
reset() {
this.result = 0;
return this;
},
getResult() {
return this.result;
}
};
// Method chaining (because each method returns `this`)
calculator.add(10).subtract(3).add(5);
console.log(calculator.getResult()); // 12
The this keyword inside a method refers to the object the method belongs to.
Checking if Properties Exist
const settings = {
theme: "dark",
fontSize: 14,
notifications: undefined
};
// `in` operator — checks if the key exists (even if value is undefined)
console.log("theme" in settings); // true
console.log("notifications" in settings); // true
console.log("language" in settings); // false
// Optional chaining — safely access nested properties
const user = { address: { city: "Portland" } };
console.log(user.address?.city); // "Portland"
console.log(user.contact?.phone); // undefined (no error)
Iterating Over Objects
const scores = {
math: 95,
english: 88,
science: 92
};
// Object.keys() — array of keys
console.log(Object.keys(scores)); // ["math", "english", "science"]
// Object.values() — array of values
console.log(Object.values(scores)); // [95, 88, 92]
// Object.entries() — array of [key, value] pairs
console.log(Object.entries(scores)); // [["math", 95], ["english", 88], ["science", 92]]
// for...in loop
for (const subject in scores) {
console.log(`${subject}: ${scores[subject]}`);
}
// Destructuring with Object.entries()
for (const [subject, score] of Object.entries(scores)) {
console.log(`${subject}: ${score}`);
}
Destructuring
Destructuring lets you extract properties into variables in one step:
const response = {
status: 200,
data: { id: 1, name: "Widget" },
headers: { "content-type": "application/json" }
};
// Basic destructuring
const { status, data } = response;
console.log(status); // 200
console.log(data); // { id: 1, name: "Widget" }
// Rename variables
const { status: httpStatus } = response;
console.log(httpStatus); // 200
// Default values
const { timeout = 5000 } = response;
console.log(timeout); // 5000 (property doesn't exist, uses default)
// Nested destructuring
const { data: { name } } = response;
console.log(name); // "Widget"
Destructuring is especially useful in function parameters:
function createUser({ name, email, role = "viewer" }) {
return { name, email, role, createdAt: new Date() };
}
const user = createUser({ name: "Alice", email: "alice@example.com" });
console.log(user.role); // "viewer"
Spread and Rest with Objects
// Spread — copy and merge objects
const defaults = { theme: "light", fontSize: 14, lang: "en" };
const userPrefs = { theme: "dark", fontSize: 16 };
const settings = { ...defaults, ...userPrefs };
console.log(settings); // { theme: "dark", fontSize: 16, lang: "en" }
// Later properties overwrite earlier ones
// Rest — collect remaining properties
const { theme, ...otherSettings } = settings;
console.log(theme); // "dark"
console.log(otherSettings); // { fontSize: 16, lang: "en" }
Computed Property Names
You can use expressions as property names:
const field = "email";
const user = {
name: "Alice",
[field]: "alice@example.com",
[`${field}Verified`]: true
};
console.log(user.email); // "alice@example.com"
console.log(user.emailVerified); // true
Object Shorthand
When a variable name matches the property name, you can use shorthand:
const name = "Alice";
const age = 28;
const email = "alice@example.com";
// Without shorthand
const user1 = { name: name, age: age, email: email };
// With shorthand — same result
const user2 = { name, age, email };
Comparing Objects
Objects are compared by reference, not by value:
const a = { x: 1 };
const b = { x: 1 };
const c = a;
console.log(a === b); // false (different objects in memory)
console.log(a === c); // true (same reference)
// To compare by value, use JSON or a deep comparison
console.log(JSON.stringify(a) === JSON.stringify(b)); // true
Freezing and Sealing
// Object.freeze() — no changes at all
const config = Object.freeze({
apiUrl: "https://api.example.com",
timeout: 5000
});
config.timeout = 10000; // silently fails (throws in strict mode)
console.log(config.timeout); // 5000
// Object.seal() — can update existing properties, but can't add/delete
const settings = Object.seal({ theme: "dark", fontSize: 14 });
settings.theme = "light"; // works
settings.lang = "en"; // silently fails
delete settings.theme; // silently fails
Common Patterns
Object as a lookup table (replacing switch/if-else)
const statusMessages = {
200: "OK",
404: "Not Found",
500: "Internal Server Error"
};
function getStatusMessage(code) {
return statusMessages[code] || "Unknown Status";
}
console.log(getStatusMessage(404)); // "Not Found"
Grouping array items by a property
const people = [
{ name: "Alice", department: "Engineering" },
{ name: "Bob", department: "Marketing" },
{ name: "Charlie", department: "Engineering" },
{ name: "Diana", department: "Marketing" }
];
const byDepartment = Object.groupBy(people, person => person.department);
console.log(byDepartment.Engineering);
// [{ name: "Alice", ... }, { name: "Charlie", ... }]
What’s Next
Objects are the foundation for more advanced JavaScript concepts. From here, you can explore the this keyword and how context works, classes and prototypal inheritance, or jump into DOM manipulation where you’ll use objects constantly to interact with web pages.