Rangle.io: React Training
gitbook
gitbook
  • Introduction
  • Setup
  • Functional JavaScript
  • ES6 constructs
    • Default Params
    • Template Literals
    • Destructuring
    • Arrow Functions
    • Promises
    • let and const
    • Modules
  • Thinking in Components
    • Atomic Design
    • Atomic Component Principles
    • Benefits of This Approach
    • The Process
    • Task #1
  • React Components
    • Stateless Components
    • Stateful Components
    • Stateful vs Stateless Components
    • Composition
    • Task #2
    • Task #3
    • Task #4
    • Task #5
  • Immutable
    • What Is Immutability?
    • The Case for Immutability
    • JavaScript Solutions
      • Object.assign
      • Object.freeze
    • Immutable.js Basics
      • Immutable.Map
        • Map.merge
      • Nested Objects
        • Deleting Keys
        • Maps are Iterable
      • Immutable.List
      • Performance
      • Persistent and Transient Data Structures
      • Official Documentation
    • Exercises
      • Task #1
      • Task #2
      • Task #3
      • Task #4
      • Task #5
      • Task #6
      • Task #7
  • Redux
    • Review of Reducers and Pure Functions
    • Redux Reducers
    • Redux Actions
    • Configuring your Application to use Redux
    • Using Redux with Components
    • Redux and Component Architecture
  • Routing
    • React Router
    • Router Redux
  • Forms
    • Redux Form
  • Testing
    • Setup
    • Components
    • Reducers
    • Actions
Powered by GitBook
On this page

Was this helpful?

  1. ES6 constructs

Destructuring

Destructuring is a way to quickly extract data out of an {} or [] without having to write much code.

To [borrow from the MDN][mdnDest], destructuring can be used to turn the following:

let foo = ['one', 'two', 'three'];

let one   = foo[0];
let two   = foo[1];
let three = foo[2];

into

let foo = ['one', 'two', 'three'];
let [one, two, three] = foo;
console.log(one); // 'one'

This is pretty interesting, but at first it might be hard to see the use case. ES6 also supports Object destructuring, which might make uses more obvious:

let myModule = {
  drawSquare: function drawSquare(length) { /* implementation */ },
  drawCircle: function drawCircle(radius) { /* implementation */ },
  drawText: function drawText(text) { /* implementation */ },
};

let {drawSquare, drawText} = myModule;

drawSquare(5);
drawText('hello');

Destructuring can also be used for passing objects into a function, allowing you to pull specific properties out of an object in a concise manner. It is also possible to assign default values to destructured arguments, which can be a useful pattern if passing in a configuration object.

let jane = { firstName: 'Jane', lastName: 'Doe'};
let john = { firstName: 'John', lastName: 'Doe', middleName: 'Smith' }
function sayName({firstName, lastName, middleName = 'N/A'}) {
  console.log(`Hello ${firstName} ${middleName} ${lastName}`)  
}

sayName(jane) // -> Hello Jane N/A Doe
sayName(john) // -> Helo John Smith Doe

The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.

For Arrays:

const fruits = ['apple', 'banana'];
const veggies = ['cucumber', 'potato'];

const food = ['grapes', ...fruits, ...veggies];
// -> ["grapes", "apple", "banana", "cucumber", "potato"]

const [fav, ...others] = food;
console.log(fav); // -> "grapes"
console.log(others); // -> ["apple", "banana", "cucumber", "potato"]

For Objects:

const member = {
  name: 'Ben',
  title: 'software developer',
  skills: ['javascrip:t', 'react', 'redux'],
};

const memberWithMetadata = {
  ...member,
  previousProjects: ['BlueSky', 'RedOcean'];
};

// behind the scenes:
const memberWithMetadata = Object.assign(member, {previousProjects: ['BlueSky', 'RedOcean']});

console.log(memberWithMetadata.name); // -> "Ben"
console.log(Object.keys(memberWithMetadata)); // -> ["apple", "banana", "cucumber", "potato"]

For function calls:

const food = ['grapes', 'apple', 'banana', 'cucumber', 'potato'];
function eat() {
  console.log(...arguments);
}

eat(...food)
// -> grapes apple banana cucumber potato

Further reading

PreviousTemplate LiteralsNextArrow Functions

Last updated 6 years ago

Was this helpful?

MDN Destructuring
ES6 In Depth: Destructuring
Destructuring Assignment in ECMAScript 6
Object.assign()