JavaScript Objects
Learn how to group data with labeled keys, read and change values, unpack data with destructuring, and copy objects safely.
1. What is an Object?
An object is a way to group related data together using labeled pairs (called key-value pairs).
💡 Think of an object like an ID Card
An ID card has labels and information next to each label: name: "Anshuman", age: 22, role: "Developer". The label is called the key, and the data is called the value.
// Creating an object with curly braces {}
const student = {
name: "Anshuman",
age: 22,
"current role": "Developer"
};
// 1. Dot notation: Best for simple keys
console.log(student.name); // "Anshuman"
console.log(student.age); // 22
// 2. Bracket notation: Needed when keys have spaces, hyphens, or come from variables
console.log(student["current role"]); // "Developer"
const keyToLookup = "name";
console.log(student[keyToLookup]); // "Anshuman"
Anshuman 22 Developer Anshuman
2. Handy Shorthands & Dynamic Keys
JavaScript lets you write less code when creating objects with variable names or dynamic labels:
const username = "Alex";
const plan = "premium";
const account = {
username, // Same as writing: username: username
[plan]: true, // Creates the key "premium: true" dynamically
greet() { // Method shorthand (a function inside an object)
return `Hi, I am ${this.username}!`;
}
};
console.log(account.username); // "Alex"
console.log(account.premium); // true
console.log(account.greet()); // "Hi, I am Alex!"
Alex true Hi, I am Alex!
3. Unpacking Objects & Merging with Spread
Destructuring lets you pull properties out of an object and save them into separate variables quickly:
const user = {
name: "Priya",
city: "Bengaluru",
skills: { primary: "React" }
};
// 1. Pulling out values (with renaming and default values):
const { name, city, role = "Engineer", skills: { primary } } = user;
console.log(name, city, role, primary);
// 2. Combining objects with the Spread Operator (...):
const defaultTheme = { mode: "dark", fontSize: 14 };
const userPrefs = { fontSize: 16 };
// userPrefs overrides fontSize, but keeps mode: "dark"
const finalSettings = { ...defaultTheme, ...userPrefs };
console.log(finalSettings);
Priya Bengaluru Engineer React
{ mode: 'dark', fontSize: 16 }
4. Essential Built-In Object Tools
JavaScript has built-in tools to grab all keys, values, or key-value pairs from an object:
const course = { title: "JavaScript", price: 0, lessons: 28 };
// Get a list of all keys (labels):
console.log(Object.keys(course)); // ["title", "price", "lessons"]
// Get a list of all values:
console.log(Object.values(course)); // ["JavaScript", 0, 28]
// Get a list of [key, value] pairs:
console.log(Object.entries(course));// [["title", "JavaScript"], ["price", 0], ["lessons", 28]]
// Safely check if a property exists in the object:
console.log(Object.hasOwn(course, "title")); // true
console.log(Object.hasOwn(course, "rating")); // false
[ 'title', 'price', 'lessons' ] [ 'JavaScript', 0, 28 ] [ [ 'title', 'JavaScript' ], [ 'price', 0 ], [ 'lessons', 28 ] ] true false
5. Protecting Objects: `Object.freeze()` vs `Object.seal()`
Sometimes you want to lock an object so nobody accidentally changes or deletes its properties:
`Object.seal()` (Lock the Structure)
You cannot add new keys or delete keys, but you can still change existing values.
const profile = { name: "Alex", score: 80 };
Object.seal(profile);
profile.score = 95; // ✅ Allowed (Changing value)
profile.newKey = "test"; // ❌ Ignored (Cannot add)
delete profile.name; // ❌ Ignored (Cannot delete)
`Object.freeze()` (Total Lockdown 🔒)
Makes the entire object completely read-only. Nothing can be added, deleted, or changed.
const config = { env: "production" };
Object.freeze(config);
config.env = "dev"; // ❌ Ignored
console.log(config.env); // "production"
6. Copying Objects: Shallow vs Deep Cloning
If an object contains another object inside it, using { ...obj } only makes a surface copy. Both objects will still share the inner nested object!
💡 Use `structuredClone()` for 100% Safe Copies
Whenever your object has nested properties (like { location: { city: "Delhi" } }), use structuredClone(obj) to ensure changes in the clone never touch the original object.
const original = {
brand: "Laptop",
specs: { ram: "16GB" }
};
// ❌ Shallow Copy: Inner object is still shared
const shallow = { ...original };
shallow.specs.ram = "32GB";
console.log(original.specs.ram); // "32GB" (Original got modified!)
// ✅ Deep Copy: Completely independent
const deep = structuredClone(original);
deep.specs.ram = "64GB";
console.log(original.specs.ram); // "32GB" (Original is protected!)
console.log(deep.specs.ram); // "64GB"
32GB 32GB 64GB
7. Quick Summary
| Tool | What it does | Example |
|---|---|---|
Object.keys() |
Returns list of all property names | ["name", "age"] |
Object.values() |
Returns list of all values | ["Anshuman", 22] |
Object.entries() |
Returns list of [key, value] pairs |
[["name", "Anshuman"]] |
Object.hasOwn(obj, key) |
Checks if a key exists in the object | true / false |
Object.freeze(obj) |
Makes object completely read-only | Locks values and keys |
structuredClone(obj) |
Makes a 100% independent deep copy | Safe for nested data |
8. Objects Interview Deck
Test your knowledge on Object.freeze limitations, computed keys, prototype vs own properties, and destructuring defaults:
9. Practice Challenge
🎯 Coding Challenge: Objects & Safe Cloning
1. Pull out name, role, and the nested stars count from dev using destructuring.
2. Verify that stats has the key "stars" using Object.hasOwn().
3. Make an isolated deep copy of dev with structuredClone(), change stats.repos = 30 on the copy, and verify the original repos count is still 25.