39

I'm just getting started with React Native and getting used to JSX syntax. Is that what I'm talking about? Or am I talking about TypeScript? Or... ES6? Anyway...

I've seen this:

const { foo } = this.props;

Inside a class function. What is the purpose of the curly braces and what's the difference between using them and not using them?

Varrick
  • 627
  • 1
  • 6
  • 11
  • 2
    its called [Destructuring](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) – elreeda Aug 04 '16 at 13:27

2 Answers2

42

It is destructuring assignment.

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Example (ES6):

var person = {firstname: 'john', lastname: 'doe'};

const firstname = person.firstname;
const lastname = person.lastname;

// same as this
const { firstname, lastname } = person;

You can find more info at MDN

EDIT: also for developers familiar with Python language it can be interesting to compare with Python unpacking syntax. Python2.7:

>>> _tuple = (1, 2, 3)
>>> a, b, c = _tuple
>>> print(a, b, c)
(1, 2, 3)

With new feature of Python3, like PEP 3132 you can also do following:

>>> _range = range(5)
>>> a, *b, c = _range
>>> print(a, b, c)
0 [1, 2, 3] 4

Examples are added, because knowing already similar approach from other languages you can grasp JS idea more quicker.

wolendranh
  • 4,202
  • 1
  • 28
  • 37
  • 1
    Looks like it could be right to me, although I guess by "app" you meant "person"? And I guess "first_name" and "last_name" shouldn't have underscores. But I get what you mean! – Varrick Aug 04 '16 at 13:19
  • @Varrick , yes, typos. underscores are there not to get error about same variable names. updated example. – wolendranh Aug 04 '16 at 13:25
  • 3
    It makes sense when you're declaring more-than-1 variable like this: `const { firstname, lastname } = person;` But what relevance does it have with only 1 variable, like this: `const { new_person } = person;` – Phil Johnston Feb 13 '19 at 21:18
  • What is Python doing here? – Robin Métral Mar 01 '19 at 07:47
  • 1
    @robinmetral "Examples are added, because knowing already similar approach from other languages you can grasp JS idea more quicker." – wolendranh Mar 01 '19 at 09:53
0

Yes this is destructuring assignment feature of ECMASCRIPT 6

For Example :

const { createElement } = React
const { render } = ReactDOM

const title = createElement('h1', {id: 'title', className: 'header'}, 'Hello World')

render(title, document.getElementById('react-container'))

here ^

React == { 
  cloneElement  : function(){ ... },
  createElement : function(){ ... },
  createFactory : function(){ ... }, 
... }
Mike Lyons
  • 1,748
  • 2
  • 20
  • 33
Apoorv
  • 222
  • 2
  • 9