Destructuring en JS

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.

TLDR;

#1 Array destructuring

Array destructuring is very much similar and straight forward, you can 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

Also Read: All you need to know about swapping two variables in JavaScript

#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

To read more about Rest operator: Understanding The Rest Operator In Javascript

#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.

Publicado por

Juan Pablo Fuentes

Formador de programación y bases de datos