3

Consider this:

var i = 0;
var isEight = false;

while(true){
    if( i === 8) {
        isEight = true;
        break;
    }
    i++;
}

versus this:

var i = 0;

while(true){
    var isEight = false; // moved declaration inside 
    if( i === 8) {
        isEight = true;
        break;
    }
    i++;
}

The example is contrived but you get the idea. How does Javascript respond when the declaration of isEight is brought inside the loop?

Does a new memory space get allocated every time that line runs? Will this be a serious issue if the loop runs many many times?


Update: Since alex pointed out, what about using let instead of var in this case.

6
  • isOdd should be isEight right? Commented May 12, 2016 at 12:39
  • @TryingToImprove yes, thanks for pointing it out Commented May 12, 2016 at 12:40
  • 3
    The declaration is hoisted so it's unlikely that there's any practical difference. In any case it would depend on the JS engine. Commented May 12, 2016 at 12:40
  • 3
    It would be a more interesting question if you were using let there instead of var. Commented May 12, 2016 at 12:41
  • Declaration of variable is done first anyway in Javascript so I believe they're not declared again if you put them in a loop? Commented May 12, 2016 at 12:42

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.