Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

difference between state={} and this.state={}

There is any difference between these two ways of initializing a state:

  1. state={}
  2. constructor(props) { super(props); this.state={} }

2 Answers

Dane Parchment
MOD
Dane Parchment
Treehouse Moderator 11,077 Points

This is actually a very complex question, because of how JavaScript handles this, and then the way it handle scope.

So instead of answering this question myself, which will probably take a big post just to make it understanding, I will instead link you to a much better article about the this statement in javascript.

Why 'This' in JavaScript

Admittedly the article is pretty high-level in terms of what it is talking about, so I recommend you take your time and read it slowly and carefully. Focus less on the syntax or what he is programming and more on how he uses this and how he explains what it does.

Thank you Dane Parchment, now is much more clear