31

What does this syntax mean in JavaScript (ES6 probably):

const {} = variablename;

I'm currently trying to get a grip of React. In a lot of examples I came across that syntax. For example:

const {girls, guys, women, men} = state;
Angelo A
  • 2,744
  • 6
  • 28
  • 37
  • 5
    It's called [destructuring assignment.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) – Pointy Feb 15 '16 at 17:58

1 Answers1

53

First of all, this has nothing to do with React. It's part of ECMAScript 6 (or JavaScript 2015, if you prefer).

What you see here is called Destructuring assignment:

const {girls, guys, women, men} = state;

// Is the same as

const girls = state.girls;
const guys = state.guys;
const women = state.women;
const men = state.men;


You're probably going to encounter a similar pattern while studying React:

import { methodA, methodB } from "my-module";

In this case, you have a module called my-module that is exporting some functions. With the import {} from syntax, you choose which functions you want to import. Note that this is not a destructuring assignment, although it works similarly.

Gio Polvara
  • 23,416
  • 10
  • 66
  • 62
  • 3
    Also works with arrays: `const { a, b, c } = ['A', 'B', 'C'];` – Sergio Flores Feb 15 '16 at 18:04
  • It also works in function parameters `function({ a, b }) {}` – Gio Polvara Feb 15 '16 at 18:11
  • they are called [named-parameters](https://github.com/DrkSephy/es6-cheatsheet#named-parameters) – Sergio Flores Feb 15 '16 at 18:26
  • 2
    Please notice that the import syntax is entirely different from destructuring. While it is looking similar in shorthand notation, it uses `as` instead of `:` and is not nestable. – Bergi Feb 15 '16 at 18:28
  • 2
    @Bergi you are right, but since OP was confused by destructuring I thought it could be helpful for him to learn also the import notation. I updated the answer to state that they are not the same thing. – Gio Polvara Feb 15 '16 at 18:52