1. Introduction
While working with arrays and objects sometimes we need to pull out values and assign it to distinct variables. The destructuring syntax makes it easy to do this with less code. Without destructuring it may require duplicate code. For example:
let person = { name: "James", age: 19, }; //extract data from person objects name = person.name; age = person.age;
You can observe, there will be repetitive code if there are more properties.
The destructuring assignment syntax makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
2. Object destructuring
Object destructuring syntax uses an object literal on the left side of an assignment operation. For example:
let person = { name: "James", age: 19, }; let { name, age } = person;
This will store the value of person.name
in variable name
and person.age
in variable age
.
2.1 Initialization is required in destructuring syntax
Note that you always need to initialize the statement with destructuring syntax. It will throw a SyntaxError
if you don’t do so.
var { type, name }; // SyntaxError let { type, name }; // SyntaxError const { type, name }; // SyntaxError
2.2. Can’t use null
and undefined
with destructuring syntax
If the right side of the destructuring assignment syntax expression is null
or undefined
or evaluates to null
or undefined
, an error is thrown.
let person1 = undefined; let person2 = null; let { name1, age1 } = person1; //TypeError: Cannot destructure property 'name1' of 'person1' as it is undefined. let { name2, age2 } = person2; // TypeError: Cannot destructure property 'name2' of 'person2' as it is null.
2.3. Default value in destructuring syntax
If left side of the assignment has a variable name which doesn’t exist on the object, the local variable is assigned a value of undefined
.
let person = { name: "James", age: 19, }; let { name, age, gender } = person; // gender is undefined
If you want to specify a default value, insert an equal sign (=) after the property name and specify the default value, like the following:
let person = { name: "James", age: 19, }; let { name, age, gender = "male" } = person; //default value of gender is male
2.4 Assigning to different local variable names
Sometimes there is requirement to use a different name for the variable, other than the name of the property of the object. You can specify the name after the (:) like the following:
let person = { name: "James", age: 19, }; let { name: nameOfPerson, age: ageOfPerson, gender: genderOfPerson = "male", } = person; console.log(nameOfPerson); // James console.log(ageOfPerson); // 19 console.log(genderOfPerson); // male
2.5 Nested object destructuring
The syntax for nested object destructuring is similar. You can use {} for nested object like the following:
let person = { name: "James", age: 19, address: { city: { cityName: "London", }, }, }; let { address: { city }, } = person; console.log(city.cityName); // London
3. Array destructuring
The syntax for array destructuring is similar to object destructuring. We just have to use array literal syntax ([]).
let fruits = ["apple", "orange", "grape"]; let [firstFruit, secondFruit] = fruits; console.log(firstFruit); // apple console.log(secondFruit); // orange let [ , , thirdFruit ] = fruits; console.log(thirdFruit); //grape
Similar to object destructuring, we always provide an initializer when using array destructuring with
var
,let
, orconst
.
3.1 Swapping variables using array destructuring
Without array destructuring we need a temporary variable to swap variables.
let a = 1, b = 2, tmp; tmp = a; a = b; b = tmp; console.log(a); // 2 console.log(b); // 1
But with array destructuring assignment we can do it without temporary variable.
// swapping variables in ECMAScript 6 let a = 1, b = 2; [ a, b ] = [ b, a ]; console.log(a); // 2 console.log(b); // 1
3.2 Default values in array destructuring assignment
Array destructuring assignment allows you to specify a default value for any position in the array.
let fruits = ["apple", "orange"]; let [firstFruit, secondFruit, thirdFruit = "grape"] = fruits; console.log(thirdFruit); //grape
3.3 Nested array destructuring
You can destructure nested arrays in a manner similar to destructuring nested objects.
let fruits = ["apple", ["orange", "mango"], "banana"]; let [firstFruit, [secondFruit]] = fruits; console.log(firstFruit); // "apple" console.log(secondFruit); // "orange"
3.4 Rest items
Rest items use the … syntax to assign the remaining items in an array to a particular variable.
let fruits = ["apple", "orange", "banana"]; let [firstFruit, ...restFruits] = fruits; console.log(firstFruit); // "apple" console.log(restFruits.length); // 2 console.log(restFruits[0]); // "orange" console.log(restFruits[1]); // "banana"
The first element “apple” is assigned to firstFruit
value and rest of the elements of “fruits” array are assigned to restFruits
variable which is an array.
Rest items must be the last entry in the destructured array and cannot be followed by a comma. Including a comma after rest items is a syntax error.
3.5 Destructured parameters
Destructured parameters offer an alternative to provide arguments to a function. A destructured parameter uses an object or array destructuring syntax. For example:
function setValue(name, age, options) { // your code here let { isAvailable } = options; console.log(isAvailable); // true } setValue("James", 21, { isAvailable: true, });
This is more convenient way to provide more number of parameters when number of parameters is not fixed and known in advance.
4. Conclusion
In this tutorial, we discussed destructuring assignment in JavaScript. This is a very important to know for a programmer to write concise and readable code. You may find code snippets in the interviews. So it is very important to know destructuring assignment syntax as it is frequently asked interview question. Hope this tutorial was informative. Happy learning !