JavaScript Intermediate2/16

Array Destructuring

Array Destructuring đź“‹

Why this matters: arrays are everywhere—results, coordinates, API tuples—and you often only care about the first few elements. Array destructuring lets you grab them by position in a single, self-documenting line.

Array destructuring extracts items by position, not by name.

Basic Syntax

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

// Old way
const first = colors[0];
const second = colors[1];

// New way
const [first, second, third] = colors;

console.log(first);   // "red"
console.log(second);  // "green"
console.log(third);   // "blue"

Key Difference from Objects

ObjectsArrays
Match by nameMatch by position
Uses { curly } bracesUses [ square ] brackets

Skip Elements

Use commas to skip items:

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

const [first, , third] = colors;
//           ↑ skip green

console.log(first);  // "red"
console.log(third);  // "blue"

Swap Variables (Cool Trick!)

let a = 1;
let b = 2;

[a, b] = [b, a];

console.log(a);  // 2
console.log(b);  // 1

Real-World Use: React's useState

// This is array destructuring!
const [count, setCount] = useState(0);
//      ↑        ↑
//      0th      1st element

Rest Pattern

Get "the rest" of the array:

const numbers = [1, 2, 3, 4, 5];

const [first, second, ...rest] = numbers;

console.log(first);  // 1
console.log(second); // 2
console.log(rest);   // [3, 4, 5]

Your Turn!

Extract the first and second fruits from the array.