Understanding Truthy and Falsy Values in JavaScript
Introduction
In JavaScript, every value is either truthy or falsy. This concept is important because it determines how values behave in conditional statements, such as if
conditions. Knowing truthy and falsy values helps developers write cleaner and more efficient code.
What Are Falsy Values?
Falsy values are values that evaluate to false
when used in a Boolean context (e.g., inside an if
statement).
List of Falsy Values:
JavaScript has only six falsy values:
false
- The booleanfalse
0
- The number zeroundefined
- A variable that has not been assigned a valuenull
- Represents an empty or non-existent valueNaN
- Not a number (e.g.,Math.sqrt(-1)
orparseInt("abc")
)''
or""
- An empty string
Example of Falsy Values:
if (!false) console.log("false is falsy");
if (!0) console.log("0 is falsy");
if (!undefined) console.log("undefined is falsy");
if (!null) console.log("null is falsy");
if (!NaN) console.log("NaN is falsy");
if (!'') console.log("empty string is falsy");
Output:
false is falsy
0 is falsy
undefined is falsy
null is falsy
NaN is falsy
empty string is falsy
What Are Truthy Values?
Truthy values are any values that are not falsy. If a value is not in the list of falsy values above, it is considered truthy.
Common Truthy Values:
true
- The booleantrue
- Any number except
0
(e.g.,1
,-1
,100
) - Any non-empty string (e.g.,
'hello'
,'0'
,'false'
) - Any object (
{}
,[]
) - Any function
Infinity
and-Infinity
Example of Truthy Values:
if (true) console.log("true is truthy");
if (1) console.log("1 is truthy");
if (-1) console.log("-1 is truthy");
if ('hello') console.log("non-empty string is truthy");
if ([]) console.log("empty array is truthy");
if ({}) console.log("empty object is truthy");
Output:
true is truthy
1 is truthy
-1 is truthy
non-empty string is truthy
empty array is truthy
empty object is truthy
Why Does This Matter?
Truthy and falsy values are used in conditional statements, logical operations, and default values.
Example: Checking for Empty Strings
let name = "";
if (name) {
console.log("Name exists");
} else {
console.log("Name is empty");
}
Output:
Name is empty
Since ""
(empty string) is falsy, the else
block runs.
Example: Using Logical OR (||
) for Default Values
If the first value is falsy, JavaScript takes the second value.
let username = "" || "Guest";
console.log(username); // Guest
Since ""
is falsy, "Guest"
is used as a fallback.
Example: Using Logical AND (&&
) for Conditional Execution
If the first value is truthy, JavaScript returns the second value.
console.log(true && "Hello"); // Hello
console.log(false && "Hello"); // false
Conclusion
- Falsy values:
false
,0
,undefined
,null
,NaN
,''
- Truthy values: Everything that is not falsy
- Used in: Conditions, logical operations, and default values
Understanding truthy and falsy values helps you write better and more efficient JavaScript code!