0

Here's the code:

var n = 4;
while(n) {
console.log("Hey!");
n = 5;
}

Am I right here:

n is a variable, with value 4.

while n = 4, print "Hey" in console.

change value of n to 5.

check if n = 4.

n is not equal to 4, so stop executing the code!

Where am I wrong? I'm really frustrated! Edited it a million times! And the worst thing, browser crashes every time! Please correct me!

Perceptioner
  • 153
  • 4
  • Both `4` and `5` are truthy values, so the loop just keeps on going until `n` is a falsy value, which never happens. – adeneo Jun 03 '15 at 17:29

1 Answers1

2

Am I right here:

n is a variable, with value 4.

while n = 4, print "Hey" in console.

while(n) doesn't check to see if n is 4, it checks to see if n is truthy*. Both 4 and 5 are truthy values.

To check if it's 4, use == or ===:

while (n === 4) {
    console.log("Hey!");
    n = 5;
}

(For more about == vs. ===, see this question and its answers.)


* JavaScript uses type coercion in many places, including when testing conditions for while loops and similar. So we talk about values being "truthy" (they coerce to true) or "falsey" (they coerce to false). Truthy values are all values that aren't falsey. The falsey values are 0, "", null, undefined, NaN, and of course, false.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875