By the end of this lesson, learners will:
if, while, etc.)In JavaScript, every value is either:
true in a Boolean contextfalse in a Boolean contextThis matters especially in conditions, like:
if (value) {
// This block runs if value is truthy
} else {
// This block runs if value is falsy
}
JavaScript has exactly 7 values that are considered falsy:
| Falsy Value | Description |
|---|---|
false | The Boolean false |
0 | The number zero |
-0 | Negative zero (rare) |
"" | Empty string |
null | Represents “no value” |
undefined | Declared but not assigned |
NaN | “Not a Number” (e.g. invalid math) |
Example:
let username = "";
if (username) {
console.log("Welcome back!");
} else {
console.log("Please enter your name.");
}
Since username is an empty string (a falsy value), the else block runs.
Anything that is not falsy is truthy!
That includes:
42, -7)"hello"){})[])Example:
let age = 25;
if (age) {
console.log("Age is set!");
}
age = 25 is a truthy value, so the message prints.
Let’s say you’re checking if a user typed something into a form:
let input = prompt("Enter your name:");
if (input) {
console.log("Thanks, " + input + "!");
} else {
console.log("You didn't enter anything.");
}
🧠 If the user presses “Cancel” or leaves it blank, input is falsy, and the else message appears.
"0" (string) as falsy📌 "0" is truthy because it’s a non-empty string.
if ("0") {
console.log("This is truthy!"); // ✅ Runs!
}
null and undefined are falsyThese are often returned by APIs or functions and need to be checked:
let result = undefined;
if (!result) {
console.log("Something went wrong.");
}
Boolean() to Test ValuesYou can use the Boolean() function to see if a value is truthy or falsy:
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean("hello")); // true
console.log(Boolean([])); // true
| Value | Truthy/Falsy |
|---|---|
false | Falsy |
0 | Falsy |
"" | Falsy |
null | Falsy |
undefined | Falsy |
NaN | Falsy |
"0" | Truthy |
[] | Truthy |
{} | Truthy |
"hello" | Truthy |
false, 0, "", null, undefined, NaN, and -0)Boolean() or test in an if to check truthiness