In JavaScript, 0 is a falsy value. This means that 0
equates to false
when represented as a boolean type. 1 on the other hand; or any other positive number for that matter, is not a falsy value and will equate to true
.
Here we could just set:
t = 0; // false
t = 1; // true
The problem with this is that these values are integers (numbers) and not boolean values (true or false). Using a strict equality check (===
) we'd find:
t = 0;
t == false; // true
t === false; // false
The ! operator performs a logical NOT operation on the value, and can be used as a quick way to convert any value to boolean:
t = !1;
t == false; // true
t === false; // true
Performance-wise, there is not really much difference between if (!t)
and if (t == true)
, however in minification terms this reduces our JavaScript by 7 bytes, allowing it to be downloaded ever so slightly quicker.