JS Destructuring

JavaScript Destructuring Assignment

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

It is a powerful ES6 feature that can make your code more concise and readable.


1. Array Destructuring

Array destructuring allows you to unpack values from an array into separate variables in a single expression.

Basic Array Destructuring

const fruits = ["Apple", "Banana", "Cherry"];

// Unpack the array into variables const [a, b, c] = fruits;

console.log(a); // "Apple" console.log(b); // "Banana" console.log(c); // "Cherry"

Skipping Elements

You can use a comma to skip over elements you don't need.

Skipping Elements

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

// Skip the second and fourth elements const [first, , third, , fifth] = numbers;

console.log(third); // 3

The Rest Operator (...)

You can use the rest operator (...) to assign the rest of an array to a new array variable.

Array Destructuring with Rest

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]


2. Object Destructuring

Object destructuring allows you to unpack properties from an object into variables. The variable names must match the property keys.

Basic Object Destructuring

const person = {
  firstName: "John",
  lastName: "Doe",
  age: 30
};

// Unpack properties into variables const { firstName, lastName, age } = person;

console.log(firstName); // "John" console.log(age); // 30

Renaming Variables

You can assign the property to a new variable name using a colon :.

Renaming Variables

const person = { firstName: "John", lastName: "Doe" };

// Unpack 'lastName' into a new variable called 'surname' const { firstName, lastName: surname } = person;

console.log(surname); // "Doe"

Default Values

You can provide a default value for a property in case it does not exist on the object.

Default Values

const person = { firstName: "John" };

// 'age' does not exist, so it will use the default value 25 const { firstName, age = 25 } = person;

console.log(age); // 25


Exercise

?

Given `const person = { name: 'Alice', age: 30 };`, how do you destructure the `name` property into a variable called `userName`?