1

I would like to know the difference between:

const data = this.props.content;

And

const {data} = this.props.content;

I saw it before but declaring 3 or 4 variables all together. However I've never seen it with just 1 variable.

What's the difference?

Ruffeng
  • 537
  • 7
  • 23
  • In first case you assign to `data` `.content`, in second case you get `data` property from `.content` and assign it to variable `data` - it is equivalent to `const data = this.props.content.data;` – Oleksandr T. Aug 03 '16 at 12:21
  • Oh, I think that I got it. For example if I do: `const {content} = this.props` is equivalent at `const content=this.props.content` , right? – Ruffeng Aug 03 '16 at 12:23
  • yes, you are right – Oleksandr T. Aug 03 '16 at 12:38

2 Answers2

1

It is a syntactic advantage of using the same name for your variable. It takes advantage of ES6 destructuring. I believe the example you listed should be altered slightly which illustrates and hopefully answers your question.

const data = this.props.content; // is exactly the same as
const {content} = this.props;

A nice writeup of destructuring can be found here: Some ES6+ features used in React development

Faktor 10
  • 1,868
  • 2
  • 21
  • 29
  • No, it's **not** exactly the same. The first line defines a variable called `data`, the second line defines a variable called `content`. –  Aug 03 '16 at 13:59
0

In your first example, you are setting data to be this.props.content.

Your second example is known as destructuring, which can be read about more here

You are basically creating a new variable by pulling it out of what you put on the right hand side.

Geraint
  • 3,314
  • 3
  • 26
  • 41