DEV Community

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

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.