What are destructuring assignments in JavaScript?

Destructuring assignments provide a concise way to extract data from arrays or objects. The general form of a destructuring assignment is

var {foo, bar} = {foo: "hello", bar: "world"}

This example extracts the foo and bar values from the {foo, bar} object. Destructuring assignments can also be used on arrays. For example, the following code extracts the first and second values from the array [1, 2, 3] .

var [a, b] = [1, 2, 3]

a is 1 and b is 2 .

Destructuring assignments can be used on nested arrays and objects. For example, the following code extracts the a and b values from the nested array [[1], [2], [3]] .

var [[a], [b]] = [[1], [2], [3]]

a is 1 and b is 2 .

Destructuring assignments can also be used to assign multiple values to a single variable. For example, the following code assigns the "a" and "b" values to the "a" and "b" variables, respectively.

var a, b = {a: "hello", b: "world"}

a is "hello" and b is "world" .

Destructuring assignments can be used to assign default values to variables. For example, the following code assigns the "a" value to the "a" variable and the "b" value to the "b" variable. If the "a" and "b" values are not present in the {a, b} object, then the "a" and "b" variables will be set to the respective default values.

var a = {a: "hello", b: "world"}

a is "hello" and b is "world" .

var a, b = {a: "hello", b: "world"}

a is "hello" and b is "world" .