Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript React Basics 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,869 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