null vs undefined in Boolean Context
What you'll learn: You'll confirm that both null and undefined are falsy values, even though they represent different concepts in JavaScript.
Both Are Falsy, Different Purposes
You've already learned that null and undefined are distinct types in JavaScript—null represents an intentional absence of value, while undefined means a variable hasn't been assigned yet. However, when it comes to boolean context (like in conditionals), they share an important trait: both are falsy.
This means that whether you check null or undefined in an if statement or use the Boolean() constructor, they both evaluate to false.
Seeing Them in Action
// Both convert to false
Boolean(null); // false
Boolean(undefined); // false
// Both fail conditional checks
if (null) {
console.log("This won't run");
}
if (undefined) {
console.log("This won't run either");
}
// Double negation confirms they're falsy
!!null; // false
!!undefined; // false
Why This Matters
Even though null and undefined mean different things conceptually, JavaScript treats them the same way in boolean operations. This is useful because you can check for "no value" without worrying which specific type it is:
let userInput = null;
if (!userInput) {
console.log("No input provided"); // This runs
}
The same check works whether userInput is null, undefined, or any other falsy value.
Key Takeaway: Both null and undefined are falsy values—they evaluate to false in boolean contexts, despite representing different kinds of "nothing" in JavaScript.