0%

javascript-falsy-values

Falsy values in JavaScript

JavaScript has the following falsy values. When used in a boolean context, they will be coerced to false.

Value Type Description
null Null The keyword null — the absence of any value.
undefined Undefined undefined — the primitive value.
false Boolean The keyword false.
NaN Number NaN — not a number.
0 Number The Number zero, also including 0.0, 0x0, etc.
-0 Number The Number negative zero, also including -0.0, -0x0, etc.
0n BigInt The BigInt zero, also including 0x0n, etc. Note that there is no BigInt negative zero — the negation of 0n is 0n.
“” String Empty string value, also including '' and ``.
document.all Object The only falsy object in JavaScript is the built-in document.all.

注意:falsyvalue在if(...)中返回false。

Truthy values

除了上面的Falsy values,剩下的都是truthy values.

Truthy values actually ==false

注意,有些值虽然是truthy values,但是它们竟然==fasle,所以,永远不要在JS中使用==!.
以下这些比较结果都是true。至于原因嘛,请看这篇

1
2
3
4
5
6
7
console.log('0' == false); // true
console.log(new Number(0) == false); // true
console.log(new Boolean(false) == false); // true
console.log(new String('0') == false); // true
console.log([] == false); // true
console.log([[]] == false); // true
console.log([0] == false); // true

Reference: https://developer.mozilla.org/en-US/docs/Glossary/Falsy