In JavaScript, a value is considered “truthy” if it evaluates to true when evaluated in a boolean context. Conversely, a value is considered “falsy” if it evaluates to false when evaluated in a boolean context.
Here’s a breakdown of truthy and falsy values in JavaScript:
Truthy values:
- Non-empty strings: Any string with at least one character.
- Non-zero numbers: Any number except 0, including negative numbers and decimals.
- true: The boolean value true.
- Objects: Any non-null object or array, including empty objects and arrays.
- Functions: Any non-null function.
Falsy values:
- Empty strings: A string with no characters, represented as
''
or""
. - 0: The number zero.
- NaN: Not-a-Number, a special value resulting from invalid operations.
- false: The boolean value false.
- null: The absence of any value or object.
- undefined: A variable that has not been assigned a value, or a function with no return value.
- Document.all: A legacy property that evaluates to false in modern browsers.
Here’s a simple illustration:
if ('hello') {
console.log('Truthy'); // This will be printed
}
if (0) {
console.log('Falsy');
} else {
console.log('Falsy'); // This will be printed
}
Understanding truthy and falsy values is important in JavaScript, especially when working with conditional statements or type coercion.