Welcome to our comprehensive guide on ES6 Destructuring! In this tutorial, we'll explore this powerful feature of JavaScript, learn why it's useful, and dive into practical examples that will help you master it.
Destructuring allows us to extract data from arrays, objects, and maps in a more intuitive and concise way. It simplifies syntax, makes your code more readable, and promotes code reusability.
Let's start with destructuring arrays. Here's an example:
let [a, b, c] = [1, 2, 3];
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3In the above example, we've used destructuring to assign values from an array to variables a, b, and c. This is an example of array pattern matching.
Destructuring objects works similarly, but with properties instead of array indices:
let user = { name: 'John', age: 30 };
let { name, age } = user;
console.log(name); // Output: John
console.log(age); // Output: 30Destructuring can also be used with nested objects and arrays:
let nested = {
user: {
name: 'John',
age: 30,
},
data: [1, 2, 3],
};
let { user: { name, age }, data: [first, second] } = nested;
console.log(name); // Output: John
console.log(age); // Output: 30
console.log(first); // Output: 1
console.log(second); // Output: 2Destructuring can also be used to swap variable values:
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // Output: 2
console.log(b); // Output: 1If a variable in a destructuring assignment doesn't have a corresponding value, it'll receive a default value:
let user = null;
let { name = 'Guest' } = user;
console.log(name); // Output: GuestIn ES6, we can use the rest operator ... to gather all remaining values in an array or object:
let arr = [1, 2, 3, 4, 5];
let [a, b, ...rest] = arr;
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(rest); // Output: [3, 4, 5]let obj = { a: 1, b: 2, c: 3, d: 4, e: 5 };
let { a, b, ...rest } = obj;
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(rest); // Output: { c: 3, d: 4, e: 5 }What is the purpose of Destructuring in JavaScript?
What is the output of the following code?
What is the output of the following code?