DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
technikhil314
technikhil314

Posted on

The unused destructuring in Javascript

I was just going through MDN and ECMA specs and trying out some cool little time saving tricks with destructuring in javascript.

Destructuring array based on index

let arr = [10, 20, 30, 40, 50];
let {0: first, 3: forth, ...rest} = arr;
console.log(first) // 10
console.log(forth) // 40
console.log(rest) // {1: 20, 2: 30, 4: 50}
Enter fullscreen mode Exit fullscreen mode

Ignore some values from array at a particular position

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

Using dynamic key in destructuring

let ab = {
  a: 10,
  b: 20
};
let a = 'a';
let {[a]: aVal} = ab;
console.log(aVal) //10
Enter fullscreen mode Exit fullscreen mode

You can even use function call, string template etc in the dynamic key

function getDynamicKey() {
    return "a";
}

let ab = {
  a: 10,
  b: 20
};
let {[getDynamicKey()]: aVal} = ab;
console.log(aVal) //10
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
vishalraj82 profile image
Vishal Raj

@technikhil314 Never came across a case of dnynamic destructuring. Meanwhile, here's my article on ES6 descructuring. Hope it helps you understand better.

Collapse
 
technikhil314 profile image
technikhil314 Author

Nice article. Thanks for sharing. I didn't get one thing though. Is there any thing wrong in my article? All I am trying to show here is rarely used cases of destructuring I know the common cases very well.

Collapse
 
vishalraj82 profile image
Vishal Raj

Nope, nothing wrong with your article.

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.