The unused destructuring in Javascript
technikhil314
Posted on June 17, 2021
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}
Ignore some values from array at a particular position
const [a, , b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // 3
Using dynamic key in destructuring
let ab = {
a: 10,
b: 20
};
let a = 'a';
let {[a]: aVal} = ab;
console.log(aVal) //10
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
đź’– đź’Ş đź™… đźš©
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
javascript Unlocking Better JavaScript Performance: Avoid These Common Pitfalls 🚀
November 24, 2024
javascript Goodbye Exceptions! Mastering Error Handling in JavaScript with the Result Pattern
November 22, 2024