Search code examples
javascriptloopswhile-loopinfinite

Why does this javascript loop return infinitely?


Can someone please explain to me why the following code returns an infinite loop rather than redefining foo?

var foo = 2;

while (foo = 2) {
   foo = 3;
}

console.log('foo is ' + foo);

Of course, the first time through the loop is going to run because foo indeed equals 2. However, I don't understand why to keeps running; after the first time through foo should now be set to 3, the parameter should return false, and console.log('foo is ' + foo); should print foo is 3.

Clearly I am missing something here.


Solution

  • You are assigning the value 2 to foo instead of comparing it in the condition here:

    while (foo = 2)

    Change it to:

    while (foo == 2)