Truthy and falsy values in JavaScript
Last updated: September 27, 2022.
The terms truthy and falsy refers to the Boolean value type – true
or false
– that a value is converted to in a logical statement.
In total, there are seven falsy values in JavaScript:
- Numeric
0
- BigInt
0n
- The value
null
- The non-value
undefined
- The Boolean value
false
- Not a number:
NaN
- Empty string:
""
All other values are truthy!
Truthy and falsy in logical statements
Truthy and falsy values are important in logical statements, such as if…else conditionals.
The if condition accepts a true
or false
Boolean value or converts whatever is passed into it to true
or false
. If the value is true
, the statement is run.
This means that if a falsy value is passed in, the if statement will not run:
if (2022) { console.log("With truthy value"); // Logs message to console } if (null) { console.log("With falsy value"); // No output } if (undefined) { console.log("With falsy value"); // No output } if ("JavaScript") { console.log("With truthy value"); // Logs message to console }
In practice, the conversion of values to truthy or falsy is useful for only running an if statement if a process has resulted in a value being assigned to a variable:
const userInput1 = "Some comments"; const userInput2 = null; if (userInput1) { console.log("Comments = " + userInput1) } else { console.log("User did not enter any comments") } // Output: Comments = Some comments if (userInput2) { console.log("Comments = " + userInput2) } else { console.log("User did not enter any comments") } // Output: User did not enter any comments