What are Truthy and Falsy Values?
In JavaScript, every value can be treated as either true or false when used in a condition (if, while, ternary operator, etc.).
-
Truthy values behave like
true. -
Falsy values behave like
false.
JavaScript automatically converts values to a boolean when evaluating conditions. This process is called Type Coercion.
Falsy Values
There are only a few falsy values in JavaScript:
false
0
-0
0n
"" // Empty string
null
undefined
NaN
Example
if (0) {
console.log("This will run");
} else {
console.log("0 is falsy");
}
Output:
0 is falsy
Truthy Values
Everything that is not falsy is truthy.
Examples:
true
1
-1
"hello"
"0"
[]
{}
function(){}
Example
if ("JavaScript") {
console.log("String is truthy");
}
Output:
String is truthy
Common Interview Examples
Example 1: Non-empty String
let username = "Saravanan";
if (username) {
console.log("Username exists");
}
Output:
Username exists
Because a non-empty string is truthy.
Example 2: Empty String
let username = "";
if (username) {
console.log("Username exists");
} else {
console.log("Username is empty");
}
Output:
Username is empty
Because an empty string is falsy.
Example 3: Checking Login Credentials
const username = "Saravanan";
const password = "1234";
if (username && password) {
console.log("Login data available");
} else {
console.log("Missing credentials");
}
Output:
Login data available
Both values are non-empty strings, so they are truthy.
Example 4: Empty Array
if ([]) {
console.log("Array is truthy");
}
Output:
Array is truthy
Many beginners expect an empty array to be falsy, but it is truthy.
Example 5: Empty Object
if ({}) {
console.log("Object is truthy");
}
Output:
Object is truthy
An empty object is also truthy.
Quick Reference Table
| Value | Truthy/Falsy |
|---|---|
false |
Falsy |
0 |
Falsy |
"" |
Falsy |
null |
Falsy |
undefined |
Falsy |
NaN |
Falsy |
1 |
Truthy |
"hello" |
Truthy |
"0" |
Truthy |
[] |
Truthy |
{} |
Truthy |
Easy Rule to Remember
JavaScript has only a handful of falsy values. Everything else is truthy.
When in doubt, ask yourself:
Boolean(value)
Examples:
Boolean(0); // false
Boolean(""); // false
Boolean("hello"); // true
Boolean([]); // true
Boolean({}); // true
Understanding truthy and falsy values is essential because they are used extensively in conditions, loops, logical operators (&&, ||), and real-world application development.
References:
https://www.geeksforgeeks.org/javascript/explain-the-concept-of-truthy-falsy-values-in-javascript/
https://stackoverflow.com/questions/35642809/understanding-javascript-truthy-and-falsy
https://frontend.turing.edu/lessons/module-1/js-truthy-falsy-expressions.html
Top comments (0)