Destructured variable from array (JS)

Quick hack for JavaScript cracks

Grab the first element of an array.

Say we create an array of variables, something like:


const theboys = ['butcher', 'hughie', 'soldier boy'];

Then we want to grab the first element of the array (if it exists):


const first = theboys[0];
console.log(first);
// butcher

What if the original array was empty?


const vought = [];
const first = vought[0];
console.log(first);
// undefined

We can do the same thing with destructuring and the rest parameter:


const theboys = ['butcher', 'hughie', 'soldier boy'];
const [first] = theboys;
console.log(first);
// butcher

Again, what if the original array was empty?


const vought = [];
const [first] = vought;
console.log(first);
// undefined

Same end result.

We can continue by accessing the ”rest” of the elements of the array using the rest parameter:


const [first, ...rest] = theboys;
console.log(first);
// butcher
console.log(rest);
// [hughie, soldier boy]

Mike North uses this in a GraphQL Tutorial, where he does something like this:


const [firstUser] = db.getAllUsers();
if (!firstUser) throw new Error();
return firstUser;

An interesting side note is that this will work with strings as well:


const myfriend = 'jimmy';
const [first, ...rest] = myfriend;
console.log(first);
// 'j'
console.log(rest);
// ['i','m','m','y']