In JavaScript, every value is either “truthy” or “falsy” when used in a boolean context — like inside an if statement. This helps you write cleaner and shorter conditions, but it can also be confusing if you’re not sure what counts as truthy or falsy.
What Are Falsy Values?
Falsy values are values that behave like false in a condition. Here’s the full list:
false
0
-0
0n // BigInt zero
'' // empty string
null
undefined
NaN
Example:
if (0) {
console.log('This won’t run');
} else {
console.log('0 is falsy');
}
What Are Truthy Values?
Everything else is truthy — including:
- Non-empty strings (
'hello') - Numbers other than 0 (
42,-7) - Arrays (
[]) - Objects (
{}) - Functions
if ('hello') {
console.log('This will run'); // 'hello' is truthy
}
Why It Matters
Understanding truthy/falsy values helps you write shorter, readable code:
const name = '';
const defaultName = name || 'Guest';
console.log(defaultName); // 'Guest' — because '' is falsy
Another example:
function isValid(value) {
return !!value; // Converts to true or false
}
Common Pitfall: 0 and ”
Sometimes 0 or '' are valid values, but JavaScript treats them as falsy. Be careful!
const score = 0;
if (!score) {
console.log('No score'); // Even though score is 0
}
Use === for Safer Checks
If you only want to check for null or undefined, use strict comparison:
if (value === null || value === undefined) {
// Safer than relying on falsy logic
}
Conclusion
Understanding truthy and falsy values is key to writing clean and bug-free JavaScript. It allows you to simplify conditions, but be careful — not everything that looks “empty” is actually false. Use these rules wisely to keep your logic solid and your code readable.
Post a Comment