//First code example
const [value_1, value_2, value_3] = ["item_1", "item_2", "item_3"]
console.log(value_1);
console.log(value_2);
console.log(value_3);
//Second code example
const [fruits, vegetables] = [
[{"name": "Orange"}, {"name": "Grapes"}, {"name": "Banana"}],
[{ "name": "Potato" }, { "name": "Onion" }, { "name": "Lady fingers" }]
];
console.log(fruits);
console.log(vegetables);
In the code snippet, we have created an array that consists of three items and we want to extract these items and assign them to three variables while creating it.
In the second code example, we have an array that consists of two items. The first item has the different objects of fruits and the second item has different objects of vegetables. So when creating it we want to assign fruits array and vegetable array to the different variables. Before ES6 we used to do that by using array indexes as below
const fruits_vegetables = [
[{"name": "Orange"}, {"name": "Grapes"}, {"name": "Banana"}],
[{ "name": "Potato" }, { "name": "Onion" }, { "name": "Lady fingers" }]
];
const fruits = fruits_vegetables[0];
const vegetables = fruits_vegetables[0]
But using ES6 we can do that while creating our array as shown in the code snippet. It is also called Array Destructuring where we extract multiple array values.
Live Demo
const [score, subject, chapter] = [
90,
{"name": "Math", "code": "M01"},
"Arithmetic"
];
console.log(score);
console.log(subject);
console.log(chapter);
let [a, b, c, d] = ["a", "b", "c", "d"];
//the above code is equivalent to
const data = ["a", "b", "c", "d"];
a = data[0];
b = data[1];
c = data[2];
d = data[3];
const [data_1, data_2 = 'item_2'] = ['item_1'];
console.log(data_1);
console.log(data_2);
const [data_1, ,data_2] = ['value_1', 'value_2', 'value_3'];
console.log(data_1); // -> 'value_1'
console.log(data_2); // -> 'value_3'
0 Comments