JavaScript contains what are called falsy and truthy values, each of which resolves to a
Falsy values are values that resolve to the Boolean false
.
In JavaScript, we have 6 falsy values:
false
0
(zero)
‘’
or “”
(empty string)
null
undefined
NaN
All these return false
when they are evaluated.
false
If we write the following:
// bool.jsif(false) {console.log("yes")}
Our code editor will indicate unreachable code. This is because the if
statement evaluates the condition to true
, and because the if
has false
, the log statement would never be displayed.
$ node bool
Nothing is displayed. This is because false
is false.
0
(zero)The number 0
is evaluated to a false
.
// bool.jsif(0) {console.log("yes")}else {console.log("no")}
no
will be printed because 0 is false
, so the else
part will be run.
‘’
or “”
(empty string)An empty string is evaluated to be false
.
// bool.jsif("") {console.log("yes")} else {console.log("no")}
Here, again, no
will be printed.
null
null
is evaluated to be false
. null
is used when we don’t want to assign a value yet to a variable. Mind you, the type of on null
returns an object. So, if you want to check whether a variable initialized with null
has been initialized with a value, null
will return false
.
// bool.jslet variable = nullif(variable) {console.log("yes, initialzed")}else {console.log("no, not yet")}variable = 90if(variable) {console.log("yes, initialzed")}else {console.log("no, not yet")}
The first part will log no, not yet
while the second part will log yes, initialized
.
undefined
undefined
is assigned to a variable whose value has not been initialized. It resolves to false
.
// bool.js
let undefVar
if(unDef) {
console.log("yes, initialzed")
}else {
console.log("no, not yet")
}
unDef = 900
if(unDef) {
console.log("yes, initialzed")
} else {
console.log("no, not yet")
}
NaN
This is a number just like 0, and it resolves to false. NaN
occurs when a number is divided by another data type.
// bool.jslet nanVar = 9/"str"if(nanVar) {console.log("yes")} else {console.log("no")}
NaN
is a falsy value, so no
will be printed.