Truthy and Falsy
In JavaScript, values can be categorized as either “truthy” or “falsy” based on their inherent truthfulness when evaluated in a boolean context. These values are often encountered when working with conditional statements and logical operations.
Truthy Values:
Values that are considered truthy will evaluate to true
when used in a boolean context. Examples of truthy values include:
- Non-empty strings
- Non-zero numbers
- Objects
- Arrays
- Functions
- Any value that is not falsy
Falsy Values:
Values that are considered falsy will evaluate to false
when used in a boolean context. Examples of falsy values include:
- An empty string (
""
) - The number
0
null
undefined
false
NaN
(Not-a-Number)
Usage in Conditional Statements:
Truthy and falsy values are often used in conditional statements to control the flow of a program. For example:
let value = "Hello";
if (value) {
console.log("Value is truthy");
} else {
console.log("Value is falsy");
}
In this case, since "Hello"
is a truthy value, the output will be Value is truthy
.
Understanding truthy and falsy values is crucial when working with conditionals, logical operations, and evaluating expressions in JavaScript. It helps you write concise and effective code that behaves as expected.
It’s important to remember that a non-boolean value only follows this “truthy”/“falsy” coercion if it’s actually coerced (usually implicitly) to a boolean.