JS fsr 140223 29/03/23

const length = 4;
const numbers = [];
for (var i = 0; i < length; i++) {

}

numbers.push(i + 1);
console.log(numbers);

2 Likes

@pradeepprabhu225
The output of the above code will be:

[5]

This is because the for loop doesn’t actually do anything except count up to the value of length . After the loop finishes, the code adds the value of i + 1 (which is 5 ) to the end of the numbers array using the push() method. So the numbers array contains only one element, which is 5 . The console.log() statement then outputs this array to the console.

2 Likes

For loop has its own environment, so numbers. push cant access the local environment of loop, Always remember in scope chain ,execution always happens from inner scope to outer scope not vice versa, so in this case for loop is just running till the length of the condition, for loop here is just like a vehicle without any accelerator