Array Destructuring / Object Destructuring

Array destructuring allows you to unpack values from arrays into separate variables.

Image description

Basic Example

const array = [1, 2, 3];
const [a, b, c] = array; console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
Enter fullscreen mode
Exit fullscreen mode

Skipping Values

const array = [1, 2, 3, 4];
const [a, , b] = array;  console.log(a); // 1
console.log(b); // 3
Enter fullscreen mode
Exit fullscreen mode

Using Rest Operator

const array = [1, 2, 3, 4, 5];
const [a, b, ...rest] = array; console.log(a); // 1
console.log(b); // 2
console.log(rest); // [3, 4, 5]
Enter fullscreen mode
Exit fullscreen mode

Object destructuring allows you to extract properties from objects into variables.

Image description

Basic Example

const obj = { x: 1, y: 2, z: 3 };
const { x, y, z } = obj; console.log(x); // 1
console.log(y); // 2
console.log(z); // 3
Enter fullscreen mode
Exit fullscreen mode

Renaming Variables

const obj = { x: 1, y: 2 };
const { x: a, y: b } = obj; console.log(a); // 1
console.log(b); // 2 
Enter fullscreen mode
Exit fullscreen mode

Default Values

const obj = { x: 1 };
const { x, y = 2 } = obj; console.log(x); // 1
console.log(y); // 2 
Enter fullscreen mode
Exit fullscreen mode

Nested Destructuring

const obj = { name: 'John', address: { city: 'New York', state: 'NY' }
};
const { name, address: { city, state } } = obj; console.log(name); // John
console.log(city); // New York
console.log(state); // NY 
Enter fullscreen mode
Exit fullscreen mode

Function Parameters

Destructuring can also be used to simplify the handling of function parameters, especially when dealing with options objects.

function greet({ name, age }) { console.log(`Hello, my name is ${name} and I am ${age} years old.`);
} const person = { name: 'Alice', age: 25 };
greet(person); // Hello, my name is Alice and I am 25 years old. 
Enter fullscreen mode
Exit fullscreen mode

These are some of the common ways to use destructuring in JavaScript. It can make your code cleaner and more readable by reducing the amount of boilerplate code required to extract values from arrays and objects.


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Here are some essential factors to consider when selecting a hosting service and domain name.