How to destructure an array and objects in JavaScript

Master destructuring values in JavaScript

The destructuring syntax allows us to extract multiple values based on the property name from objects or arrays.

var num = [1,2,3,4,5];
var [a, b] = num;
console.log(a, b); //1,2
var obj = {
name : "JavaScript Jeep",
work : "Blogging"
};
var {name, work} = obj;
console.log(name, work);

Array Destructuring

Values in arrays are destructured based on their index. The variable can be named anything you want, but the variable name associated with the index is how it is assigned.

var fruits = ["🍎", "🍌", "🍍"];
var [apple, banana, pineapple] = fruits;
console.log(apple, banana, pineapple); // "🍎", "🍌", "🍍"

We can also assign values to variables that are already declared.

var apple = "apple";
var banana = "banana";
[apple, banana] = ["🍎", "🍌"]
console.log(apple, banana); // "🍎", "🍌"

If there are more variables than the length of the array, the value of the remaining variables becomes undefined.

var arr = [1]
var [a, b] = arr;
console.log(a, b); 1, undefined

Using the rest operator in destructing

The rest operator (...) allows you to accumulate the remaining items that aren’t destructured.

var numbers = [1,2,3,4,5,6];
var [a, b, ...rest] = numbers;
console.log(a, b, rest); // 1, 2, [3,4,5,6]

When using the rest operator, the rest element should be the last element, otherwise, it will throw a syntax error.

var [a, ...b, c] = [1, 2, 3]; // error because rest operator is not last element
var [a, ...b,] = [1, 2, 3]; // error because trailing comma after rest operator

Setting default values to the variable

var fruits = ["🍎", "🍍"];
//without default value
var [apple, pineapple, banana] = fruits;
console.log("without default value ", apple, pineapple, banana); // "🍎", "🍍", undefined
// with default value
var [apple, pineapple, banana= "🍌" ] = fruits;
console.log("With default value", apple, pineapple, banana); // "🍎", "🍍", "🍌"

Skipping values of an array

We can skip an element in a specific index by not specifying any variable name.

var num = [1,2,3];
var [one,,three] = num;
console.log(one, three); 1, 3

Tip: With array destructing, we can easily swap values.

var a = 10,b = 20;
[b, a] = [a, b]
console.log(a, b); 20, 10

Object destructuring

We can extract data from the properties of an object using object destructuring. Here, the name of the variable is matched with the property of the object, and the corresponding property value is retrieved from the object and assigned to the variable.

Example 1:

var user = {name : "Ram", age : 20};
var {name, age} = user;
console.log(name, age); // "Ram", 20

Example 2:

var {name, age} = {name: "Ram", age : 20};
console.log(name, age); // "Ram", 20

If the variable name doesn’t match the property of the object, then the value of the unmatched variable will be undefined.

var {name, age, salary} = {name: "Ram", age : 20};
console.log(salary); //undefined

Using the rest operator

We can use a rest operator with object destructuring to store all of the remaining properties to the rest operator variable.

var user = {name: "Mike", age : 30, weight : 150};
var {name, ...details} = user;
console.log(name, details); // "Mike" , {age: 30, weight : 30}

Destructuring a variable that is already declared

Imagine that we have two variables, name and age, and a user object with:

var name , age; 
var user = {name: "Ram", age : 20}; 

We can’t do {name, age} = user; because { is the first token, so JavaScript thinks it is the start of a block.

To solve this, we should enclose the expression with brackets.

var name , age; 
var user = {name: "Ram", age : 20}; 
({name, age}) = user;

Assigning to new variable names

var user = {name : "Ram"};
var {name: userName} = user;
userName; // "Ram"
console.log(userName);

The code above takes the name property from the user object, creates a new variable with the name userName, and assigns the value to the userName variable.

Tip: We can use a new variable name when the property of the object is an invalid identifier name.

var user = {"user-name" : "Mike"};
var {"user-name": userName} = user;
userName; //Mike
console.log(userName);

Assigning default value

The default value can be assigned to a variable if the property is not present in the object.

var user1 = {name : "Mike", nickName : "mic"};
var {name1, nickName1="Noob Master"} = user1;
console.log(nickName1); // "Noob Master"
//If the property not present
var user2 = {name : "Ram"};
var {name2, nickName2="Noob Master"} = user2;
console.log(nickName2); //"Noob Master"

Using both default values and new variable names

var user = {};
var {name: userName = "Default Name"} = user;
console.log(userName); // "Default Name"

Using Object Destructuring as function arguments

function logUser(user)
{
var name = user.name;
var age = user.age;
console.log(name, age);
}
var user = {name : "Mike", age : 20};
logUser(user); // "Mike", 20

The code above can be simplified into the code below.

function logUser( {name, age} )
{
console.log(name, age);
}
var user = {name : "Mike", age : 20};
logUser(user); // "Mike", 20

Using the default value and new variable names in function argument destructuring

function logUser( {name:userName, age: userAge = 30} )
{
console.log(userName, userAge);
}
var user = {name : "Mike"};
logUser(user); // "Mike" , 30

The above logUser method will throw an error if we call the method without any argument. If we don’t pass an argument, it will try to destructure undefined and, therefore, throws an error. To resolve this:

function logUser({name: Name="Jack", age: Age = 30} = {})
{
console.log(Name, Age);
}
logUser(); // Jack 30

Free Resources

Attributions:
  1. undefined by undefined