The Complete Guide to JavaScript Destructuring ES6

The Complete Guide to JavaScript Destructuring ES6

The JavaScript destructuring assignment syntax is expressive, compact and more readable that makes it possible to “destructured” (upwarp) values from arrays or properties from objects, into different variables.

JavaScript Destructuring Expression (demo)

[a, b] = [50, 100];

console.log(a);
// expected output: 50

console.log(b);
// expected output: 100

[a, b, ...rest] = [10, 20, 30, 40, 50];

console.log(rest);
// expected output: [30,40,50]

We can use JavaScript Destructuring in so many different ways.

#1 Array destructuring

Array destructuring is very much similar and straight forward, you use an array literal on the left-hand-side of an assignment expression. Each variable name on the array literal maps to the corresponding item at the same index on the destructured array.

#1.1 Basic variable assignment.

let foo = ['one', 'two', 'three'];

let [red, yellow, green] = foo;
console.log(red); // "one"
console.log(yellow); // "two"
console.log(green); // "three"

#1.2 Assignment separate from the declaration.

You can assign a variable value via destructuring separate from the variable’s declaration. For example:- first, you declare the variables then you assign separately.

// declare the variables
let a, b;
// then you assign separately
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2

#1.3 Default values

You can also set a default value if the unpacked value is undefined

let a, b;
// setting default values
[a = 5, b = 7] = [1];
console.log(a); // 1
console.log(b); // 7

In the above example, we are setting the default values to a and b. In that case if a or b values are undefined it will assign default values 5 to a and 7 to b

#1.4 Swapping variables

It is possible to swap two variables in one destructuring expression. Isn’t that cool?

let a = 1;
let b = 3;

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

If you want to swap variables without destructuring it is going to require a temporary variable or XOR swap algorithm but with destructuring

I got this one JavaScript Destructuring

#1.5 Parsing an array returned from a function

Yes, it is possible to destructure on returning an array from a function.

function c() {
  return [10, 20];
}

let a, b; 
[a, b] = c(); 
console.log(a); // 10
console.log(b); // 20

In the above example, c() returns the values [1, 2] as its output can be parsed in a single line with using destructuring.

#1.6 Ignoring returned values/Skipping Items

You can also skip some returned values that are not useful for you. For example:-

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

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

In rare cases, if you want to ignore all values.

[,,] = c();

Yes, I know this is not going to happen ever, but as this is a complete guide I have to tell you everything.

#1.7 Assigning the rest of an array to a variable

When you are using array destructuring you can assign remaining part of an array to a single variable.

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

Be careful to trailing comma syntax error, It will occur if trailing comma is used on the left-hand side with a rest element:

let [a, ...b,] = [1, 2, 3];
// SyntaxError: rest element may not have a trailing comma

#1.8 Nested Array Destructuring

Like objects, you can also do nested destructuring with arrays. Here is an example below

const color = ['#FF00FF', [255, 0, 255], 'rgb(255, 0, 255)'];

// Use nested destructuring to assign red, green and blue
const [hex, [red, green, blue]] = color;

console.log(hex, red, green, blue); // #FF00FF 255 0 255

#2 Object destructuring

#2.1 Basic Object destructuring

let x = {y: 22, z: true};
let {y, z} = x;

console.log(y); // 22
console.log(z); // true

#2.2 Assignment without declaration

You can assign variables using destructuring without separating it from its declaration. It means you don’t have to create a x variable in the above example.

let y, z;

({y, z} = {y: 1, z: 2});

Note: The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration. {a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}

Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

Source MDN

#2.3 Assigning to new variable names

You can also change the name of variables while using object destructuring like an example below:-

let o = {p: 22, q: true};
let {p: foo, q: bar} = o;

console.log(foo); // 22 
console.log(bar); // true

For example, var {p: foo} = o takes from the object o the property named p and assigns it to a local variable named foo.

#2.4 Default values

You can also set a default value if the unpacked object value is undefined

let {a = 10, b = 5} = {a: 3};

console.log(a); // 3
console.log(b); // 5

#2.5 Assigning to new variables names and providing default values together.

let {a: aa = 10, b: bb = 5} = {a: 3};

console.log(aa); // 3
console.log(bb); // 5

#2.6 Nested object and array destructuring

const metadata = {
  title: 'Scratchpad',
  translations: [
    {
      locale: 'de',
      localization_tags: [],
      last_edit: '2014-04-14T08:43:37',
      url: '/de/docs/Tools/Scratchpad',
      title: 'JavaScript-Umgebung'
    }
  ],
  url: '/en-US/docs/Tools/Scratchpad'
};

let {
  title: englishTitle, // rename
  translations: [
    {
       title: localeTitle, // rename
    },
  ],
} = metadata;

console.log(englishTitle); // "Scratchpad"
console.log(localeTitle);  // "JavaScript-Umgebung"

#2.7 Computed object property names and destructuring

You can compute a property name while changing its name using object destructuring.

let key = 'z';
let {[key]: foo} = {z: 'bar'};

console.log(foo); // "bar"

In the above example, we computed the key variable and change its name to foo

#2.8 Combined Array and Object Destructuring

Array and objects can be combined in Destructuring.

const props = [
  { id: 1, name: 'Fizz'},
  { id: 2, name: 'Buzz'},
  { id: 3, name: 'FizzBuzz'}
];

const [,, { name }] = props;

console.log(name); // "FizzBuzz"

Syntax is the same for all destructuring assignment, but on the left-hand side of the assignment to define what values to unpack from the sourced variable. For Example:-

let x = [1, 2, 3, 4, 5];
let [y, z] = x;
console.log(y); // 1
console.log(z); // 2

If you liked it please comment and share.

javascript es6

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

What is ES6, What is ECMAScript & Why You Should Learn it? – JavaScript ES6 for Beginners

Learn what ES6 is, what ECMAScript is, and why it is important to learn for writing modern JavaScript.

Learn Modern JavaScript ES6 | ES7 | ES8

In this article we are going to Learn Modern JavaScript [ ES6 | ES7 | ES8 ] , so as you know JavaScript is a scripting language that was introduced for

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

JavaScript ES6: Var, Let, and Const || ES6 Variable Declarations Explained

Learn the 2 new keywords that ES6 brings for declaring variables: let & const, when and why to use them instead of the old var keyword. JavaScript ES6: Var, Let, and Const || ES6 Variable Declarations Explained

JavaScript ES6: Var, Let, and Const || ES6 Variable Declarations Explained

JavaScript ES6: Var, Let, and Const || ES6 Variable Declarations Explained. Learn the 2 new keywords that ES6 brings for declaring variables: let & const, when and why to use them instead of the old var keyword.