-1
var m = 5;
if (m) {
    document.write(m);
}

In my view, m is not a bool type, therefore, this if statement will not be executed. However, I do see the value of m printed on my screen. Why?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Nick WEI
  • 33
  • 5

1 Answers1

2

You should read about truthy values (MDN).

In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, 0n, "", null, undefined, and NaN).

Any number other than 0 is truthy, so if(5) is the same as if(true).

Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
  • Then there's the browser-specific falsy value, `document.all`, which is falsy despite being an object. That's for historical reasons... :-) – T.J. Crowder Dec 05 '21 at 09:37