Yogesh Chauhan's Blog

Array destructuring and Object destructuring in JavaScript

in JavaScript on November 16, 2020

With the destructuring assignment syntax you can extract values from arrays, or even properties from objects, into variables.

When you are working in React or Angular or any other JS framework, you’ll find this feature really helpful.

This is how we can access arrays elements without destructuring:


var array_element_1 = array[0];
var array_element_2 = array[1];
...
...

With destructuring assignment, we can make the same code more concise and readable.

Like this:


var [array_element_1, array_element_2] = array;

Syntax


[ var_1, var_2, var_3, ..., var_N ] = array;

As you might have figured it out, the above code will assign variables all the variables to items(elements) in array.

Also, we can declare variables using var, let, or const at the time of assignment.

For e.g.


var [ var_1, var_2, var_3, ..., var_N ] = array;
let [ var_1, var_2, var_3, ..., var_N ] = array;
const [ var_1, var_2, var_3, ..., var_N ] = array;

This syntax that looks similar to array or object literals. Isn’t it?

💡 This capability of JavaScript is similar to features present in languages such as Perl and Python.

Array destructuring

Assign values from an array to variables 


const priorities = [1, 2, 0];

const [gym, work, movie] = priorities;
console.log(gym); // 1
console.log(work); // 2
console.log(movie); // 0

Declare variables and then assign values

As we saw earlier, we can declare the variables and then assign the values.


let a, b;

[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2

Assign Default Values (Be Aware!)

If the variables have values assigned to them, then it will get replaced when you use the destructuring assignment.


let a, b;

[a="Yogesh", b="Jon"] = [1];
console.log(a); // 1
console.log(b); // Jon

Swap variable values

Destructuring assignment makes swapping way easier. You don’t even need the third variable to swap values of two variables.

Like this:


let y = "Yogesh";
let j = "Jon";

[y, j] = [j, y];
console.log(y); // Jon
console.log(j); // Yogesh

Also, we can swap the elements in arrays


const array = ["Yogesh", "Blog", "Chauhan's"];
[array[2], array[1]] = [array[1], array[2]];
console.log(array); 
// [ 'Yogesh', "Chauhan's", 'Blog' ]

Parsing an array returned from a function


function top3() {
  return [1, 2, 3];
}

let a, b, c; 
[a, b, c] = top3(); 
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

It’s never been easier to get the returned array and save it to variables. ES6 rocks!

What if we just want to ignore some values?


function top3() {
  return [1, 2, 3];
}

let a, c; 
[a, , c] = top3(); 
console.log(a); // 1
console.log(c); // 3

Just leave a black while assigning the values and it won’t save it.

What is you leave all elements black?


function top3() {
  return [1, 2, 3];
}

let a, c; 
[ , , ] = top3(); 
console.log(a); // undefined
console.log(c); // undefined

It doesn’t have variables to save the values and we are calling the variables which do not have any values so we get undefined.

What if we just pass one variable and nothing else, no blanks?


function top3() {
  return [1, 2, 3];
}

let a, c; 

[a] = top3(); 
console.log(a); // 1

[c] = top3(); 
console.log(c); // 1

Every time we do that, it will just take the first value and assign it to that variable passed. So, we won’t be able to access the further values.

What is we have 10 values, or 50, or 500?

I don’t think it’s a good idea to write down all the elements to get the values. 

JavaScript does have the solution though, not a complete solution but it does offer one.


function top3() {
  return [1, 2, 3];
}

let a, c; 
[a, ...c] = top3(); 
console.log(a); // 1
console.log(c); // [2, 3]

Object destructuring

Assign values from an object to variables 


const priorities = {
    gym: 1,
    work: 2,
    movie: 0
};

const {gym, work, movie} = priorities;

console.log(gym); // 1
console.log(work); // 2

Assign values to variables that are not declared


let a, b;

({a, b} = {a: 1, b: 2});

Assign to new variable names

An object property can be unpacked from an object and assigned to a variable with a different name than the object property.


const book = {pages: 200, read: true};
const {pages: totalPages, read: isRead} = book;
 
console.log(totalPages); // 200 
console.log(isRead); // true

Default values

A variable can be assigned a default in object same as we saw earlier in array.

In the case that the value unpacked from the object is undefined.


const {bookToRead = 10, alreadyRead = 5} = {bookToRead: 3};

console.log(bookToRead); // 3
console.log(alreadyRead); // 5

Assigning to new variables names and providing default values

A property can be both

1. unpacked from an object and assigned to a variable with a different name and

2. assigned a default value in case the unpacked value is undefined.

This is the same case as we in the array earlier.


const {bookToRead: BR = 10, alreadyRead: AR = 5} = {bookToRead: 3};

console.log(BR); // 3
console.log(AR); // 5

There are so many possibilities when it comes to deconstructing an object or an array.

Credit: MDN Docs


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Content types in DrupalDrupalCreate a galley with overlapping images using CSS gridCSSAdd animation to your skills bar using CSSCSSColleague UI Basics: Accessing the user interfaceColleagueWhat Does Host-Based Intrusion Detection System (HIDS) Mean and What Are Some Advantages Over NIDS?Miscellaneous6 Different Functions to Sort Arrays in PHPPHP