JavaScript Intermediate3/16

Destructuring in Functions

Destructuring in Function Parameters

Why this matters: modern JavaScript code often passes big objects into functions (options, props, config). Destructuring right in the parameter list clearly documents what the function needs and avoids repetitive access inside the body.

You can destructure directly in the function parameters. This is extremely common in modern JavaScript!

The Problem

// Without destructuring
function displayUser(user) {
  console.log(user.name);
  console.log(user.age);
  console.log(user.email);
  // Repeating "user." everywhere!
}

The Solution

// With destructuring in parameters
function displayUser({ name, age, email }) {
  console.log(name);
  console.log(age);
  console.log(email);
  // Much cleaner!
}

displayUser({ name: "Alex", age: 25, email: "alex@email.com" });

Why This Matters

  1. Self-documenting: Function signature shows what properties it needs
  2. Cleaner code: No repetitive object access
  3. Very common: Used heavily in React components

Real-World Example: React Component

// This is how React components work!
function UserCard({ name, avatar, bio }) {
  return (
    <div>
      <img src={avatar} />
      <h2>{name}</h2>
      <p>{bio}</p>
    </div>
  );
}

Default Values

Prevent undefined errors:

function greet({ name = "Guest", age = 0 }) {
  return `Hello ${name}, you are ${age}`;
}

greet({});  // "Hello Guest, you are 0"
greet({ name: "Alex" });  // "Hello Alex, you are 0"

With Array Destructuring

function getFirst([first, second]) {
  return first;
}

getFirst(["apple", "banana"]);  // "apple"

Your Turn!

Create a function that takes { brand, year } and returns a formatted string.