The easiest way is to remember the 7 values that are evaluated to "false".
Here they are (some of them are obvious, some are a bit surprising):
- undefined
- null
- false
- +0
- -0
- NaN
- "" (empty string)
This behavior can be used in different ways, e.g. shortening the check if a jQuery selector returns elements or not:
if ($('#foo').length > 0) {
...
}
can also be checked as follows (because jQuery returns an array of length 0 which is evaluated to "false"):
if ($('#foo').length) {
...
}
Note that you can produce subtle bugs if you are not aware of the evaluation rules.
Example:
function printLineItem(article, price) {
if (article && price) {
console.log("Article: " + article + "Price: " + price);
}
}
printLineItem("Amiga 500", 999);
printLineItem("5 bitcoins voucher for next purchase", 0);
Bad luck for the customer, he won't get the voucher :-(