DEV Community

Tanay Patel
Tanay Patel

Posted on • Updated on

Destructuring in JavaScript

Hi,
I was brushing up my concepts on JavaScript and found some of the types of destructing in JavaScript.
The destructuring assignment syntax is a JavaScript expression that makes it possible to destructure/unpack values from arrays, or properties from objects, into distinct variables.

Here are some of the destructuring examples below,

Destructuring Arrays

var [a, b] = [1, 2];
console.log(a, b);
// => 1 2
Enter fullscreen mode Exit fullscreen mode

*Omit certain values

var [a, , b] = [1, 2, 3];
console.log(a, b);
// => 1 3
Enter fullscreen mode Exit fullscreen mode

*Combine with spread/rest operatior (accumulates the rest of the values)

var [a, ...b] = [1, 2, 3];
console.log(a, b);
// => 1 [ 2, 3 ]
Enter fullscreen mode Exit fullscreen mode

*Swap variables easily without temp

var a = 1, b = 2;
[b, a] = [a, b]
console.log(a, b);
//=> 2 1
Enter fullscreen mode Exit fullscreen mode

*Advance deep arrays

var [a, [b, [c, d]]] = [1, [2, [[[3, 4], 5], 6]]];
console.log("a:", a, "b:", b, "c:", c, "d:", d);
// => a: 1 b: 2 c: [ [ 3, 4 ], 5 ] d: 6
Enter fullscreen mode Exit fullscreen mode

Destructuring objects

var { user: x } = { user: 5 };
console.log(x);
// => 5
Enter fullscreen mode Exit fullscreen mode

*More values

var { prop: x, prop2: y } = { prop: 5, prop2: 10 };
console.log(x, y);
// => 5 10
Enter fullscreen mode Exit fullscreen mode

*Short-hand syntax

var { prop, prop2 } = { prop: 5, prop2: 10 };
console.log(prop, prop2);
// => 5 10
Enter fullscreen mode Exit fullscreen mode

Deep objects

var {
    prop: x,
    prop2: {
        prop2: {
            nested: [, , b]
        }
    }
} = { prop: "Hello", prop2: { prop2: { nested: ["a", "b", "c"] } } };
console.log(x, b);
// => Hello c
Enter fullscreen mode Exit fullscreen mode

Using as method parameters

var foo = function ({ prop: x }) {
    console.log(x);
};

foo({ invalid: 1 });
foo({ prop: 1 });
// => undefined
// => 1
Enter fullscreen mode Exit fullscreen mode

Nested advanced examples

var foo = function ({
    prop: x,
    prop: {
        prop2: {
            nested: b
        }
    }
}) {
    console.log(x, ...b);
};
foo({ prop: "Hello", prop2: { nested: ["a", "b", "c"] } }});
// => Hello a b c
Enter fullscreen mode Exit fullscreen mode

Rest and defaults

var ajax = function ({ url = "localhost", port: p = 80 }, ...data) {
    console.log("Url:", url, "Port:", p, "Rest:", data);
};

ajax({ url: "someHost" }, "additional", "data", "hello");

ajax({}, "additional", "data", "hello");
// => Url: localhost Port: 80 Rest: [ 'additional', 'data', 'hello' ]

ajax({});
// => Url: localhost Port: 80 Rest: []

// Doesn't work due to trying to destructure undefined
ajax();
// => Uncaught TypeError: Cannot match against 'undefined' or 'null'

// To fix this we need to have default value for parameter in function
// Note: See the `= {}` at the end, saying default empty object if the first argument
var ajax = ({ url: url = "localhost", prot: p = 80 } = {}) => {
    console.lgo("Url:", url, "Port:", p);
};

// Now this works.
ajax();
// => Url: localhost Port: 80

ajax({});
// => Url: localhost Port: 80

ajax({ port: 8080 });
// => Url: localhost Port: 8080

ajax({ url: "someHost", port: 8080 });
// => Url: someHost Port: 8080
Enter fullscreen mode Exit fullscreen mode

Similar to _.pluck

var users = [
    { user: "Name1" },
    { user: "Name2" },
    { user: "Name2" },
    { user: "Name3" }
];
var names = users.map(({ user }) => user);
console.log(names);
// => [ 'Name1', 'Name2', 'Name2', 'Name3' ]
Enter fullscreen mode Exit fullscreen mode

Usage in for..of loops

var users = [
    { user: "Name1" },
    { user: "Name2", age: 2 },
    { user: "Name2" },
    { user: "Name3", age: 4 }
];

for (let { user, age = "DEFAULT AGE" } of users) {
    console.log(user, age);
}

// => Name1 DEFAULT AGE
// => Name2 2
// => Name 2 DEFAULT AGE
// => Name 3 4
Enter fullscreen mode Exit fullscreen mode

You can find more about destructuring @ Destructuring assignment - developer.mozilla.org

Source:

  • developer.mozilla.org
  • FrontendMasters

by Tanay Patel

Top comments (0)