Get values using destructuring assignment.
Environment and Prerequisite
- Javascript
Destructuring Assignment
Definition
Destructuring assignment
: It is an syntax which can unpack values from elements of array or properties in object.- There are many examples on link in below ‘Reference’
Simple Examples
Array Destructuring
let arr = [1, 2, 3, 4, 5];
let [a, b, ...c] = arr;
console.log(arr);
console.log(a);
console.log(b);
console.log(c);
[ 1, 2, 3, 4, 5 ]
1
2
[ 3, 4, 5 ]
Object Destructuring
let object = {
a: 1,
b: "test",
c: [1, 2],
d: { name: "test", age: 28 },
};
// Key must be same
let { a, b, c, d } = object;
/* Assign to different variable name example
let { a: e, b: f, c: g, d: h } = object;
*/
console.log(a);
console.log(b);
console.log(c);
console.log(d);
1
test
[ 1, 2 ]
{ name: 'test', age: 28 }
Usage
- By using this
destructuring assignment
, we can return multi values from function. Technically, its function return object or array and receives its values in caller using destructuring assignment.
Array Destructuring Example
function test() {
return [1, 2, 3, 4, 5];
}
let [a, b, ...c] = test();
console.log(a);
console.log(b);
console.log(c);
1
2
[ 3, 4, 5 ]
Object Destructuring Example
function test() {
let object = {
a: 1,
b: "test",
c: [1, 2],
d: { name: "test", age: 28 },
};
return object;
}
let { a, b, c, d } = test();
console.log(a);
console.log(b);
console.log(c);
console.log(d);
1
test
[ 1, 2 ]
{ name: 'test', age: 28 }