skip to Main Content

As far as I know, it is not possible to redeclare a const array.

However when I declare arr inside the loop, it seems that arr is redeclare for each iteration.
I don’t understand this situation, does for loop create a new scope for each time i change?

for (let i=0; i<5; i++){
  const arr = [];
  arr.push(i);
  console.log(arr[0]);
}
//console: 0 1 2 3 4

3

Answers


  1. Constants cannot change through re-assignment or be re-declared. Since you’re just adding to the array you aren’t doing either of those.

    Login or Signup to reply.
  2. If a variable is declared inside a loop, JS will allocate fresh memory for it in each iteration, even if older allocations will still consume memory.

    const arr only exists in block scope, you get a new variable next iteration. Because each loop iteration gets its own execution context.

    Login or Signup to reply.
  3. The way variables are handled by the JS runtime is, every iteration of the loop creates a separate variable (variable binding). So 5 iterations of the for loop creates 5 separate variables (separate one for each iteration).

    For exact details of how the variable declaration is treated based on the keyword and type of looping mechanism used, please check this.
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for…of#description

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search