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 React Basics (2018) Understanding State Create a Stateful Component

Why is an object property initialized with = ?

I know the objects have key:value or methods, or array but I do not understand in the video when Guil created state like

state = {

}

what do we call that sort? I heard key: value, arrays, booleans but is it object assigned to a property? If so why we use equal?

1 Answer

Michael Hulet
Michael Hulet
47,912 Points

state is a property on the Counter class. Properties are just like normal variables, but they're values contained by an object. Take this code for example:

const a = 1; // a is now 1

const obj = {}; // obj is a new object
obj.a = 2; // obj.a is 2

const otherObj = {};
otherObj.a = 3; //otherObj.a is 3

console.log(a); // Logs 1
console.log(obj.a); // Logs 2
console.log(otherObj.a); // Logs 3

Notice how in all those cases, the = operator was used to assign the value to each property, just like it was the normal constant at the top. In the video, state is a property on this (and this equal to the new Counter object). When each new Counter is created, it will be given a property called state, which will be equal to another new object, which itself will have a property called score, which will start as 0