[a, b] = [50, 100];
console.log(a);
// expected output: 50
console.log(b);
// expected output: 100
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest);
// expected output: [30,40,50]
Array destructuring is very much similar and straight forward, you use an array literal on the left-hand-side of an assignment expression. Each variable name on the array literal maps to the corresponding item at the same index on the destructured array.
let foo = ['one', 'two', 'three'];
let [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"
You can assign a variable value via destructuring separate from the variable’s declaration. For example:- first, you declare the variables then you assign separately.
// declare the variables
let a, b;
// then you assign separately
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
You can also set a default value if the unpacked value is undefined
let a, b;
// setting default values
[a = 5, b = 7] = [1];
console.log(a); // 1
console.log(b); // 7
In the above example, we are setting the default values to a
and b
. In that case if a
or b
values are undefined
it will assign default values 5
to a
and 7
to b
It is possible to swap two variables in one destructuring expression. Isn’t that cool?
let a = 1;
let b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
If you want to swap variables without destructuring it is going to require a temporary variable or XOR swap algorithm but with destructuring
Yes, it is possible to destructure on returning an array from a function.
function c() {
return [10, 20];
}
let a, b;
[a, b] = c();
console.log(a); // 10
console.log(b); // 20
In the above example, c()
returns the values [1, 2]
as its output can be parsed in a single line with using destructuring.
You can also skip some returned values that are not useful for you. For example:-
function c() {
return [1, 2, 3];
}
let [a, , b] = c();
console.log(a); // 1
console.log(b); // 3
In rare cases, if you want to ignore all values.
[,,] = c();
Yes, I know this is not going to happen ever, but as this is a complete guide I have to tell you everything.
When you are using array destructuring you can assign remaining part of an array to a single variable.
let [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]
Be careful to trailing comma syntax error, It will occur if trailing comma is used on the left-hand side with a rest element:
let [a, ...b,] = [1, 2, 3];
// SyntaxError: rest element may not have a trailing comma
Like objects, you can also do nested destructuring with arrays. Here is an example below
const color = ['#FF00FF', [255, 0, 255], 'rgb(255, 0, 255)'];
// Use nested destructuring to assign red, green and blue
const [hex, [red, green, blue]] = color;
console.log(hex, red, green, blue); // #FF00FF 255 0 255
let x = {y: 22, z: true};
let {y, z} = x;
console.log(y); // 22
console.log(z); // true
You can assign variables using destructuring without separating it from its declaration. It means you don’t have to create a x
variable in the above example.
let y, z;
({y, z} = {y: 1, z: 2});
Note: The parentheses
( ... )
around the assignment statement are required when using object literal destructuring assignment without a declaration.
{a, b} = {a: 1, b: 2}
is not valid stand-alone syntax, as the{a, b}
on the left-hand side is considered a block and not an object literal.However,
({a, b} = {a: 1, b: 2})
is valid, as isvar {a, b} = {a: 1, b: 2}
Your
( ... )
expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.Source MDN
You can also change the name of variables while using object destructuring like an example below:-
let o = {p: 22, q: true};
let {p: foo, q: bar} = o;
console.log(foo); // 22
console.log(bar); // true
For example, var {p: foo} = o
takes from the object o
the property named p
and assigns it to a local variable named foo
.
You can also set a default value if the unpacked object value is undefined
let {a = 10, b = 5} = {a: 3};
console.log(a); // 3
console.log(b); // 5
let {a: aa = 10, b: bb = 5} = {a: 3};
console.log(aa); // 3
console.log(bb); // 5
const metadata = {
title: 'Scratchpad',
translations: [
{
locale: 'de',
localization_tags: [],
last_edit: '2014-04-14T08:43:37',
url: '/de/docs/Tools/Scratchpad',
title: 'JavaScript-Umgebung'
}
],
url: '/en-US/docs/Tools/Scratchpad'
};
let {
title: englishTitle, // rename
translations: [
{
title: localeTitle, // rename
},
],
} = metadata;
console.log(englishTitle); // "Scratchpad"
console.log(localeTitle); // "JavaScript-Umgebung"
You can compute a property name while changing its name using object destructuring.
let key = 'z';
let {[key]: foo} = {z: 'bar'};
console.log(foo); // "bar"
In the above example, we computed the key variable and change its name to foo
Array and objects can be combined in Destructuring.
const props = [
{ id: 1, name: 'Fizz'},
{ id: 2, name: 'Buzz'},
{ id: 3, name: 'FizzBuzz'}
];
const [,, { name }] = props;
console.log(name); // "FizzBuzz"
Syntax is the same for all destructuring assignment, but on the left-hand side of the assignment to define what values to unpack from the sourced variable. For Example:-
let x = [1, 2, 3, 4, 5];
let [y, z] = x;
console.log(y); // 1
console.log(z); // 2
If you liked it please comment and share.
#javascript #es6