Destructuring Arrays and Objects with JavaScript

Examples using ES6 syntax + a Saab.

Basic Array Destructuring:

let arr = [1, 2, 3, 4, 5, 6];

let [first, second, third] = arr;

console.log(first, second, third);

➜  destructuring git:(master) ✗ node prac2.js
1 2 3

Also:

let [first, second] = [1, 2, 3, 4, 5];
console.log(first, second);

//returns:
➜  destructuring git:(master) ✗ node prac2.js 
1 2

Object Destructuring:

//Say you have a nice little Saab object: 

let car = {
    make: 'saab',
    model: 900,
    year: 1995
};

//You can destructure the above like so: 

let { make, model, year } = car;
console.log(make, model, year);

//console returns:
➜  destructuring git:(master) node prac2.js 
saab 900 1995

For more examples check out the MDN article here. Also, there's a great post by Sarah Chima Atuonwu - another excellent primer to destructuring with Arrays and Objects.

Have fun! :)