Objects

📖 Concept

Objects are collections of key-value pairs. They are the fundamental building block of JavaScript — almost everything is an object (arrays, functions, dates, regex, etc.).

Creating objects: Object literals {}, new Object(), Object.create() Accessing properties: Dot notation obj.key or bracket notation obj["key"] The this keyword: Inside a method, this refers to the object the method belongs to (in most cases).

Key methods: Object.keys(), Object.values(), Object.entries(), Object.assign(), Object.freeze(), Object.seal(), Object.hasOwn()

🏠 Real-world analogy: An object is like a filing cabinet. Each drawer has a label (key) and contains something (value). You can add drawers, remove them, or look inside them.

💻 Code Example

codeTap to expand ⛶
1// Creating objects
2const person = {
3 name: "Alice",
4 age: 25,
5 hobbies: ["reading", "coding"],
6 address: {
7 city: "New York",
8 zip: "10001"
9 },
10 // Method shorthand
11 greet() {
12 return `Hi, I'm ${this.name}`;
13 }
14};
15
16// Accessing properties
17console.log(person.name); // "Alice"
18console.log(person["age"]); // 25
19const key = "hobbies";
20console.log(person[key]); // ["reading", "coding"]
21
22// Dynamic keys
23const field = "email";
24const userData = {
25 [field]: "alice@example.com", // Computed property name
26 [`get${field.charAt(0).toUpperCase() + field.slice(1)}`]() {
27 return this[field];
28 }
29};
30
31// Object methods
32console.log(Object.keys(person)); // ["name", "age", "hobbies", "address", "greet"]
33console.log(Object.values(person)); // ["Alice", 25, [...], {...}, fn]
34console.log(Object.entries(person)); // [["name","Alice"], ["age",25], ...]
35
36// Shallow copy
37const copy = { ...person }; // spread
38const copy2 = Object.assign({}, person);
39
40// Freeze vs Seal
41const config = Object.freeze({ api: "/v1", debug: false });
42// config.api = "/v2"; // ❌ Silently fails (or throws in strict mode)
43
44const settings = Object.seal({ theme: "dark" });
45settings.theme = "light"; // ✅ Can modify existing
46// settings.lang = "en"; // ❌ Can't add new properties
47
48// Check property existence
49console.log("name" in person); // true
50console.log(person.hasOwnProperty("name")); // true
51console.log(Object.hasOwn(person, "name")); // true (modern)
52
53// Iterating
54for (const [key, value] of Object.entries(person)) {
55 console.log(`${key}: ${value}`);
56}

🏋️ Practice Exercise

Mini Exercise:

  1. Create a "bank account" object with deposit and withdraw methods using this
  2. Write a function to deep clone an object (handle nested objects and arrays)
  3. Write a function that merges two objects, with the second overriding the first
  4. Create an object with a computed property name based on a variable

⚠️ Common Mistakes

  • this in arrow functions doesn't refer to the object — arrow functions inherit this from the enclosing scope

  • Shallow copy with spread {...obj} doesn't deep clone — nested objects are still references

  • Using delete obj.prop is slow — set to undefined if performance matters, or use destructuring to exclude

  • Checking property existence with if (obj.prop) fails when the value is falsy — use in operator or Object.hasOwn()

  • Object.freeze() is shallow — nested objects can still be modified

💼 Interview Questions

🎤 Mock Interview

Mock interview is powered by AI for Objects. Login to unlock this feature.