← JS Mastery | Module 4: Objects & Arrays Objects: Creation, Properties & Methods
Module 4

Objects: Creation, Properties & Methods

⏱ 20 min read ● Beginner 🆓 Free

Objects — Key-Value Stores

Objects are JavaScript's fundamental data structure for grouping related data and behavior. Think of an object as a container with named slots — each slot has a key (name) and a value.

// Object literal — the most common way to create objects
const person = {
  name: "Alice",
  age: 30,
  city: "New York",
  isActive: true
};

// Accessing properties
console.log(person.name);       // "Alice" — dot notation
console.log(person["age"]);     // 30 — bracket notation
const key = "city";
console.log(person[key]);       // "New York" — dynamic key access

// Adding/updating properties
person.email = "alice@example.com";   // add new
person.age = 31;                       // update existing

// Deleting properties
delete person.isActive;
console.log(person.isActive);  // undefined

// Checking if property exists
console.log("name" in person);         // true
console.log("phone" in person);        // false
console.log(person.hasOwnProperty("age")); // true

Shorthand & Computed Properties

// Property shorthand (ES6) — when key = variable name:
const name = "Alice";
const age = 30;
const person = { name, age };  // same as { name: name, age: age }

// Computed property names:
const prefix = "get";
const obj = {
  [prefix + "Name"]() { return this.name; },
  [`${prefix}Age`]() { return this.age; }
};

// Methods in objects:
const calculator = {
  value: 0,
  add(n) {    // method shorthand (ES6)
    this.value += n;
    return this;  // return this for chaining
  },
  subtract(n) {
    this.value -= n;
    return this;
  },
  result() {
    return this.value;
  }
};
// Method chaining:
const answer = calculator.add(10).add(5).subtract(3).result();
console.log(answer);  // 12

Object Methods — Built-in

const user = { name: "Alice", age: 30, role: "admin" };

// Object.keys() — array of property names
console.log(Object.keys(user));    // ["name", "age", "role"]

// Object.values() — array of values
console.log(Object.values(user));  // ["Alice", 30, "admin"]

// Object.entries() — array of [key, value] pairs
console.log(Object.entries(user));
// [["name","Alice"], ["age",30], ["role","admin"]]

// Object.assign() — merge/copy objects
const defaults = { theme: "dark", lang: "en" };
const userPrefs = { lang: "fr", fontSize: 16 };
const config = Object.assign({}, defaults, userPrefs);
// { theme: "dark", lang: "fr", fontSize: 16 }

// Spread operator (better than Object.assign):
const config2 = { ...defaults, ...userPrefs };

// Object.freeze() — prevent modifications
const CONSTANTS = Object.freeze({ PI: 3.14159, E: 2.71828 });
// CONSTANTS.PI = 99;  // silently fails (or errors in strict mode)

// Object.fromEntries() — convert entries back to object
const entries = [["a", 1], ["b", 2]];
const obj = Object.fromEntries(entries);  // { a: 1, b: 2 }

// Convert Map to Object:
const map = new Map([["x", 10], ["y", 20]]);
const objFromMap = Object.fromEntries(map);  // { x: 10, y: 20 }

Nested Objects & Deep Access

const company = {
  name: "TechCorp",
  address: {
    street: "123 Main St",
    city: "San Francisco",
    country: "USA"
  },
  employees: [
    { name: "Alice", role: "Engineer" },
    { name: "Bob", role: "Designer" }
  ],
  getHeadCount() {
    return this.employees.length;
  }
};

// Deep access:
console.log(company.address.city);         // "San Francisco"
console.log(company.employees[0].name);    // "Alice"
console.log(company.getHeadCount());       // 2

// Safe deep access with optional chaining:
console.log(company?.ceo?.name ?? "No CEO listed");  // "No CEO listed"

⚡ Key Takeaways

🎯 Practice Exercises

EXERCISE 1

Create a student object with name, grades array, and a getAverage() method. Add a property for school. Test all operations.

EXERCISE 2 — CHALLENGE

Write a function deepMerge(obj1, obj2) that recursively merges two objects (nested properties are merged, not overwritten).

← Recursion