DEV Community

Discussion on: 8 Ridiculously Simple Javascript Tricks Not Taught on Tutorials

Collapse
 
potouridisio profile image
Ioannis Potouridis • Edited

In addition to 'Reallocating variables', object-like destructuring of arrays is a trick I don't see that often.

const people = [
  {
    age: 33,
    name: 'John',
  },
  {
    age: 29,
    name: 'Helen',
  },
];

const { 1: secondPerson } = people;

console.log(secondPerson); // prints { age: 29, name: 'Helen' }

Or to make it even more ridiculous, you may want to destructure just the age of the secondPerson, but also keep the secondPerson object as a whole.

const { 1: secondPerson, 1: { age: secondPersonsAge } } = people;

console.log({ secondPerson, secondPersonsAge });
// prints { secondPerson: { age: 29, name: 'Helen' }, secondPersonsAge: 29 }
Collapse
 
veebuv profile image
Vaibhav Namburi

Jesus Christ, at this point I would probably have just done it in a non destructured way haha.

Pretty neat though

Some comments have been hidden by the post's author - find out more