Destructuring of Objects and Arrays in JavaScript
Destructuring of Objects and Arrays
60
Destructuring in JavaScript is a powerful technique that allows you to extract specific values from an object or an array and assign them to individual variables. This feature was introduced in ECMAScript 6 to simplify the syntax of assignments and to make the code more readable.
Destructuring of Objects:
You can destruct an object into individual variables by enclosing the keys in curly braces {}. The keys should match the property names of the object.
Here's an example:
const person = { name: 'John', age: 30, gender: 'Male' }; const {name, age, gender} = person; console.log(name); // 'John' console.log(age); // 30 console.log(gender); // 'Male'
You can also define default values while destructuring an object, in case the property doesn't exist:
const person = { name: 'John', gender: 'Male' }; const {name, age = 30, gender} = person; console.log(name); // 'John' console.log(age); // 30 (default value) console.log(gender); // 'Male'
Destructuring of Arrays:
You can destruct an array into individual variables by enclosing the variables in square brackets []. The order of the variables should match the elements of the array.
Here's an example:
const numbers = [1, 2, 3]; const [x, y, z] = numbers; console.log(x); // 1 console.log(y); // 2 console.log(z); // 3
You can also skip elements while destructuring an array:
const numbers = [1, 2, 3]; const [x, , z] = numbers; console.log(x); // 1 console.log(z); // 3
You can also use default values while destructuring an array, in case the element doesn't exist:
const numbers = [1]; const [x, y = 2, z = 3] = numbers; console.log(x); // 1 console.log(y); // 2 (default value) console.log(z); // 3 (default value)
Destructuring is a very handy feature in JavaScript, it makes the code more simple and readable, especially when dealing with large objects or arrays.
March 25, 2023