Master Destructing Values in JavaScript

Learn how to destructure array and object properties into variables in JavaScript.

Image fromย Unsplash

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

                       // Destructing array
var num = [1,2,3,4,5];
var [a, b] = num;
console.log(a, b); //1,2
                       // Destructing Object 

var obj = {
  name : "JavaScript Jeep",
  work : "Blogging"
};

var {name, work} = obj;
console.log(name, work); // "Javascript Jeep", "Blogging"

Array Destructing

Values in arrays are desctructured based on their index. The variable can be named anything you want. 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 value to already declared variables.

var apple = "apple";
var banana = "banana";

[apple, banana] = ["๐ŸŽ", "๐ŸŒ"]
console.log(apple, banana); // "๐ŸŽ", "๐ŸŒ"

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

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

Using the rest operator in destructing:

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

The restย ... operator allows you to accumulate the remaining items that arenโ€™t destructured.

When using rest operator, the rest element should be last element, otherwise it will throw Syntax Error.

var [a, ...b, c] = [1, 2, 3]; // error

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

Setting Default values to the variables:

var fruits = ["๐ŸŽ", "๐Ÿ"];

//without default value
var [apple, pineapple, banana ] = fruits;
console.log(apple, pineapple, banana); // "๐ŸŽ", "๐Ÿ", undefined 
                      // with default value
var [apple, pineapple, banana= "๐ŸŒ" ] = fruits;
console.log(apple, pineapple, banana); // "๐ŸŽ", "๐Ÿ",  "๐ŸŒ"

Skipping values of the array

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

Tips: With array destructing we can easily swap values

var a = 10,b = 20;

[b, a] = [a, b]

console.log(a, b); 20, 10

Object Destructing

We can extract data from properties of the object using object destructing. 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.

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 unmatched variable will be undefined.

var {name, age, salary} = {name: "Ram", age : 20};
salary; //undefined

Using the rest operator

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

Destructing an already declared variable

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

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

To solve this

({name, age} = user);

Assigning to new variable names

var user = {name : "Ram"};
var {name: userName} = user;

userName; // "Ram"

The above code takes name property from user and create a new variable with name userName and assign the value to userName variable.

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

var user = {"user-name" : "Mike"};  
var {"user-name": userName} = user;
userName; //Mike

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); // "mic"

               //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 Destructing as function arguments

Without destructing

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 above code can be simplified to

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

Using default value and new variable name in function argument destructing

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

The above method logUser will throw an error if we call the method without any argument. If we donโ€™t pass any argument, it tries to destructure undefined so it throws error. To resolve this:

function logUser({name: Name="Jack", age: Age = 30} = {}) 
{

console.log(Name, Age);
} 
logUser(); // Jack 30

Thanks ๐Ÿ˜Š ๐Ÿ™ for Reading ๐Ÿ“–.

Follow me JavaScript Jeep๐Ÿš™๐Ÿ’จย .

Please make a donation here. 80% of your donation is donated to someone needs food ๐Ÿฅ˜. Thanks in advance.

Leave a comment

Design a site like this with WordPress.com
Get started