Lesson 90 +20 XP

Destructuring

Destructuring

Destructuring unpacks values from arrays or objects into variables in one step.

Array destructuring

const colors = ["red", "green", "blue"];
const [first, second] = colors;
first;  // "red"
second; // "green"

Swapping variables easily

let a = 1, b = 2;
[a, b] = [b, a];
a; // 2
b; // 1

Skipping items

const [first, , third] = colors;
third; // "blue"

Object destructuring

const person = { name: "Ada", age: 36 };
const { name, age } = person;
name; // "Ada"
age;  // 36

Renaming in object destructuring

const { name: fullName } = person;
fullName; // "Ada"

Function parameter destructuring

function greet({ name }) {
  return "Hello " + name;
}
greet(person); // "Hello Ada"

TL;DR

  • Destructuring unpacks values into variables.
  • Arrays: const [a, b] = arr.
  • Objects: const { name, age } = obj.
  • Great for swapping and clean function params.