egg24
egg24

Reputation: 9

(Javascript) Why declare CONST ARRAY in LOOP doesn't cause error

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

Upvotes: 0

Views: 523

Answers (3)

Prashanth Puranik
Prashanth Puranik

Reputation: 121

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

Upvotes: 0

Lakshitha
Lakshitha

Reputation: 1542

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.

Upvotes: 0

Justin Matthews
Justin Matthews

Reputation: 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.

Upvotes: 0

Related Questions