Empty Strings vs Strings with Whitespace
You'll learn why an empty string is falsy but a string containing only spaces is truthy—a subtle distinction that can prevent bugs in your conditionals.
The Core Distinction
In JavaScript's world of truthy and falsy values, only the completely empty string '' is falsy. The moment you put anything inside those quotes—even a single space—it becomes truthy.
This catches many beginners off guard. It's easy to assume that a string with just whitespace "feels" empty and should be falsy, but JavaScript disagrees.
// The empty string is falsy
if ('') {
console.log("This won't run");
}
// A string with whitespace is truthy
if (' ') {
console.log("This WILL run!"); // Surprise!
}
if (' ') {
console.log("Multiple spaces? Still truthy!"); // Also runs
}
Why This Matters
Think of it like a box: an empty box ('') weighs nothing, but a box containing air or packing peanuts (' ') has something in it—even if that something seems insignificant. JavaScript checks: "Is there content?" Not: "Is there meaningful content?"
Boolean('') // false
Boolean(' ') // true
Boolean(' \n ') // true (newlines and spaces still count!)
// Practical example
const userInput = ' ';
if (userInput) {
console.log("User entered something!"); // This runs, even though it's just spaces
}
If you need to treat whitespace-only strings as "empty," you'd combine conditionals with methods like trim() (which you've already learned).
Key Takeaway: Only the empty string '' is falsy in JavaScript; any string containing characters—including spaces, tabs, or newlines—is truthy.