JavaScript Getting Started With ES2015 Defining Variables With let and const Using let with for Loops

Aakash Srivastav
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,610 Points

Using let with for loop

I have a doubt here with const .
If the value of button is changing after every iteration i,e button 0 , button 1 , then why he used const to declare button ?

3 Answers

Steven Parker
Steven Parker
177,727 Points

In this video, "button" is assigned inside a loop. Before the loop repeats, "button" is disposed (no longer exists).

On the next iteration, a new "button" is created. The old one is not being re-assigned.

Aakash Srivastav
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,610 Points

In the previous case , the variable status was a part of login_info object.
But here it's a seperate variable.
And if it's the only property of the button that is changing , then how will it be reassigned so that we will get a Uncaugh type error .
Please help me with example.
I am sorry . I am still confused.

Steven Parker
Steven Parker
177,727 Points

Each iteration has a different context. So this:

for (var i=0; i < 3; i++) {
  const tester = i;
  console.log(tester);
}

Is essentially the same thing as this:

{
  const tester = 0;
  console.log(tester);
}
{
  const tester = 1;
  console.log(tester);
}
{
  const tester = 2;
  console.log(tester);
}

In both cases, the constant(s) exist only between the braces.

Aakash Srivastav
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,610 Points

Oh . Thanks
I just got confused with the word "const" , I forgot that the value gets stored in stack . And it also vanished into next repitition.
Thanks again .