Question

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.

Was it helpful?

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)

OTHER TIPS

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

You are missing an equal sign (or two if you want an even stricter check)

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

You may miss "while (foo == 2)" when open the loop,

if it again prints infinity let it know me..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top