1

Can someone explain why result of this is infinite loop??

var name = true;
var soloLoop = function () {
  while (name) {
     console.log(name);
     name = false;
  }
};

soloLoop();
  • Note 1: Can be reproduced only in browser's console.
  • Note 2: Is reproducible only with variable "name".
micnic
  • 10,915
  • 5
  • 44
  • 55
Dinu
  • 390
  • 1
  • 2
  • 12

1 Answers1

6

When you declare variables in the global scope, as you're doing here, they're actually contained as properties on the global object, in this case window. window.name is something that already exists, and can only be set to a string.

When you do:

var name = true;

It's actually setting the window.name to "true". Same for name = false - it sets it to "false". Since "false" is "truthy", the while loop will never exit.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93
  • your answer does not explain why it is reproduced only if the code is running from the browser console, in simple script the loop is executed only once – micnic Sep 08 '15 at 17:22
  • 2
    It will reproduce outside of the console too, so long as it's in the global scope. The likes of jsfiddle etc won't be in the global scope. – James Thorpe Sep 08 '15 at 17:25
  • true, I was testing in the jsfiddle and Node environment :P – micnic Sep 08 '15 at 17:31