Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the for loop counter doesn't get destroyed after exiting the loop in javascript?

Tags:

javascript

for(var i=0;i<5;i++){}
alert(i);

in javascript this will get us 5 other languages like C++, java, c# .... will simply give an error that the i variable isn't defined in the context.

So why the for loop counter doesn't get destroyed after exiting the loop in javascript?

like image 922
Modar Avatar asked Jul 04 '13 17:07

Modar


People also ask

Does javascript wait for for loop to finish?

To use Javascript promises in a for loop, use async / await . This waits for each promiseAction to complete before continuing to the next iteration in the loop.

How do you exit a loop in Javascript?

The break statement breaks out of a switch or a loop. In a switch, it breaks out of the switch block. This stops the execution of more code inside the switch. In in a loop, it breaks out of the loop and continues executing the code after the loop (if any).

Are local variables made inside a loop destroyed?

1 Answer. Show activity on this post. At the end of each loop iteration, the variable goes out of scope and ceases to exist. That doesn't mean assigning a special value (such as null ) to it; it just means that the memory is available to be used by other things.

Are variables local to loops?

A local loop variable is one that exists only when the Loop Facility is invoked. At that time, the variables are declared and are initialized to some value. These local variables exist until loop iteration terminates, at which point they cease to exist.


1 Answers

This is because the JavaScript engine will move ("hoist") the variable decalaration to the top of the function no matter where it is declared inside the function1. JavaScript does not have block scope.

{
//Some code
    for(var i=0;i<5;i++){}
    alert(i);
//Some code
}

Is equivalent to:

{
  var i;
 //.. some code
 for(i=0;i<5;i++){}
    alert(i);
}

1 Unless it's the exception being caught with a catch clause; that variable is scoped to catch block.

Update

For defining block scope variables ecmascript 6 specs (javascript 1.7) introduces let. Currently this will work only in latest version of FireFox browser and in consensus stage.

<script type="application/javascript;version=1.7">
     //Some code

        for (let i = 0; i < 10; i++) {

            alert(i); // 1, 2, 3, 4 ... 9
        }

        alert(i); // Here you will get an error here saying ReferenceError: i is not defined.
    }
</script>

Fiddle

like image 50
PSL Avatar answered Nov 14 '22 23:11

PSL