intermediate Step 6 of 20

Objects and Destructuring

JavaScript Programming

Objects and Destructuring

Objects are the most fundamental data structure in JavaScript — nearly everything in JavaScript is an object or behaves like one. An object is a collection of key-value pairs (properties) that can store data and functions (methods). ES6 introduced destructuring, a powerful syntax for extracting values from objects and arrays into distinct variables. Combined with features like the spread operator, shorthand properties, and computed property names, modern JavaScript provides elegant ways to work with objects.

Creating and Using Objects

// Object literal
const person = {
    firstName: "Alice",
    lastName: "Johnson",
    age: 30,
    hobbies: ["reading", "coding"],
    address: {
        city: "New York",
        country: "USA"
    },
    // Method
    fullName() {
        return `${this.firstName} ${this.lastName}`;
    }
};

// Accessing properties
console.log(person.firstName);        // "Alice" (dot notation)
console.log(person["lastName"]);      // "Johnson" (bracket notation)
console.log(person.address.city);     // "New York"
console.log(person.fullName());       // "Alice Johnson"

// Adding/modifying properties
person.email = "alice@example.com";
person.age = 31;

// Deleting properties
delete person.email;

// Check if property exists
console.log("age" in person);              // true
console.log(person.hasOwnProperty("age")); // true

// Shorthand properties (when variable name matches key)
const name = "Bob";
const age = 25;
const user = { name, age };  // Same as { name: name, age: age }

Object Destructuring

const product = {
    id: 1,
    title: "Laptop",
    price: 999.99,
    category: "Electronics",
    specs: { ram: "16GB", cpu: "i7" }
};

// Basic destructuring
const { title, price } = product;
console.log(title);  // "Laptop"
console.log(price);  // 999.99

// Renaming variables
const { title: productName, price: cost } = product;
console.log(productName);  // "Laptop"

// Default values
const { discount = 0, title: t } = product;
console.log(discount);  // 0 (default, since product has no discount)

// Nested destructuring
const { specs: { ram, cpu } } = product;
console.log(ram);  // "16GB"

// Rest operator — collect remaining properties
const { id, ...rest } = product;
console.log(id);    // 1
console.log(rest);  // { title: "Laptop", price: 999.99, ... }

// Destructuring in function parameters
function displayProduct({ title, price, category = "General" }) {
    console.log(`${title}: $${price} (${category})`);
}
displayProduct(product);  // "Laptop: $999.99 (Electronics)"

Array Destructuring

const colors = ["red", "green", "blue", "yellow", "purple"];

// Basic
const [first, second] = colors;
console.log(first, second);  // "red" "green"

// Skip elements
const [, , third] = colors;
console.log(third);  // "blue"

// Rest operator
const [primary, ...others] = colors;
console.log(primary);  // "red"
console.log(others);   // ["green", "blue", "yellow", "purple"]

// Default values
const [a = "x", b = "y", c = "z"] = [1, 2];
console.log(a, b, c);  // 1, 2, "z"

// Swapping variables
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y);  // 2, 1

// From function returns
function getMinMax(arr) {
    return [Math.min(...arr), Math.max(...arr)];
}
const [min, max] = getMinMax([3, 1, 4, 1, 5, 9]);
console.log(min, max);  // 1, 9

Object Methods and Iteration

const scores = { Alice: 95, Bob: 87, Charlie: 92 };

// Object.keys(), values(), entries()
console.log(Object.keys(scores));     // ["Alice", "Bob", "Charlie"]
console.log(Object.values(scores));   // [95, 87, 92]
console.log(Object.entries(scores));  // [["Alice",95], ["Bob",87], ...]

// Iterating
for (const [name, score] of Object.entries(scores)) {
    console.log(`${name}: ${score}`);
}

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

// Spread operator (preferred over Object.assign)
const config2 = { ...defaults, ...userPrefs };

// Object.freeze — make immutable
const frozen = Object.freeze({ x: 1, y: 2 });
frozen.x = 10;  // Silently fails (or throws in strict mode)

// Computed property names
const field = "email";
const obj = { [field]: "alice@example.com" };
console.log(obj.email);  // "alice@example.com"

// Optional chaining with objects
const user2 = { profile: { avatar: { url: "pic.jpg" } } };
console.log(user2?.profile?.avatar?.url);  // "pic.jpg"
console.log(user2?.settings?.theme);       // undefined
Pro tip: Destructuring in function parameters is one of the most useful patterns in JavaScript. Instead of accepting a long list of positional arguments, accept a single options object and destructure it with defaults: function createUser({ name, age = 0, role = "user" } = {}) { ... }.

Key Takeaways

  • Objects store key-value pairs; access properties with dot notation or brackets for dynamic keys.
  • Destructuring (const { a, b } = obj) extracts values into variables concisely, with support for renaming and defaults.
  • The spread operator ({ ...obj }) creates shallow copies and merges objects immutably.
  • Use Object.keys(), Object.values(), and Object.entries() to iterate over objects.
  • Destructure function parameters for cleaner APIs: function f({ name, age = 0 }) { }.