The unused destructuring in Javascript

technikhil314

technikhil314

Posted on June 17, 2021

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
đź’– đź’Ş đź™… đźš©
technikhil314
technikhil314

Posted on June 17, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related