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 Components Stateful Components and Lifecycle Methods Resetting the Stopwatch

When you store seconds in a const, how come that value gets changed? Isn't const an immutable (for primitive) in ES2015?

In this video, when the teacher wanted to calculate the time in seconds, he declared a const second in render method. Now in previous ES2015 tutorials, it says when you declare a variable as const and if it holds a primitive data type, that variable is immutable. JS suppose to give you a warning, but in React this doesn't happens. Any idea why?

Thanks

3 Answers

Daniel Totten
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Daniel Totten
Full Stack JavaScript Techdegree Graduate 21,003 Points

If I'm understanding this all correctly, I think the render() method gets called every time there is a state change. Therefore, the seconds variable is created each time the render() method is called, not updated, and therefore is still immutable. I think if we put the seconds variable in a different scope, we would have to use let instead of const.

Got it, I missed that completely. Thanks Daniel

Not sure what you need, but it can be:

const obj = {}

We can't change it, but we can modify its parameters like:

// Allowed
obj.name = 'me'
// Not allow
var obj = {
  name: 'me'
}

Hi thanks for the reply, But in the video (~1:30 mins)

const seconds = Math.floor(this.state.elapsedTime / 1000);

This is a number type . So it should not get changed right?

The variables declared with "const" and "let" are "scopped", means that "seconds" doesn't exits outside any scope http://es6-features.org/#BlockScopedVariables