JavaScript React Components Stateful Components and Lifecycle Methods Resetting the Stopwatch

Janaka Bandara
Janaka Bandara
1,329 Points

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
Daniel Totten
Full Stack JavaScript Techdegree Graduate 20,997 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.

Janaka Bandara
Janaka Bandara
1,329 Points

Got it, I missed that completely. Thanks Daniel

Khoi Nguyen
Khoi Nguyen
1,269 Points

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'
}
Janaka Bandara
Janaka Bandara
1,329 Points

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