0

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.

1
  • what is that even supposed to do? Commented Apr 1, 2014 at 4:33

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

Comments

2
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;
}

2 Comments

No syntactically it is completely correct. It's a logical error.
JavaScript has a concept of "truthy" and "falsey", which means that you can use boolean logic on non-boolean values. The value 2 is truthy, so while (2) is the same as while (true).
0

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

if it again prints infinity let it know me..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.