Skip to content

Instantly share code, notes, and snippets.

@aderaaij
Last active November 13, 2017 14:16
Show Gist options
  • Save aderaaij/9df26c1788c83999dba1dd58fe744a6b to your computer and use it in GitHub Desktop.
Save aderaaij/9df26c1788c83999dba1dd58fe744a6b to your computer and use it in GitHub Desktop.
A feature I tend to forget about in es6 is the possibility to destructure arrays as well. Instead of curly brackets you use with an object, you use square brackets and as arrays do not have keys, array destructuring is based on the position of the values in the element.These are a couple of array destructuring examples from es6.io.
const details = ['Arden', 123, 'arden.nl'];
// get a bunch of values out of the details array and name them as variable
const [name, id, website] = details;
console.log(name, id, website);
const data = 'Basketball,Sports,90210,23,super,man,cool';
// We use data.split(',') which takes in the data string and returns it as an
// array which we immediately destructure with es6 array destructuring.
// When we have values that we do not call while destructuring, nothing will
// happen with them.
const [itemName, category, sku, inventory] = data.split(',');
const team = ['Cap', 'Hulk', 'Black Widow', 'Iron Man', 'Thor'];
// Here we destructure the first and second values from the team array and return
// them in variables called `captain` and `assistant`. We use the `rest` operator (`...`) to
// spread out the remaining values in an array called `players`
const [captain, assistant, ...players] = team;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment