Destructuring

What is it about

  • Syntactic sugar
  • Assigns (existing) properties to variables
  • Works for objects and arrays

Why?

  • makes it very quick to pull out a specific properties
  • allows to map properties into aliases
/* Object destructuring */

const unicorn = { name: 'pony', age: 3 };
const { name, age } = unicorn;

console.log(name); // -> 'pony'
console.log(age); // -> 3

Examples

// ES5 way
var name = unicorn.name;
var age = unicorn.age;
// Aliasing
const { name: a, age: b } = unicorn
console.log(a) // -> 'pony'
console.log(b) // -> 3
/* Array destructuring */

const ages = [3, 1, 2];
const [firstAge] = ages;
console.log(firstAge); // -> 3

Examples

// Skipping elements
const [first, , last] = ages;
console.log(first); // -> 3
console.log(last); // -> 2
Made with Slides.com