![]() |
VOOZH | about |
In JavaScript, truthy values are the values that are evaluated to be true when used in a Boolean context, such as in conditional statements or logical operations.
If you’ve ever wondered what JavaScript considers “true,” here’s the simple answer: any value that is not explicitly falsy (like false, 0, null, undefined, NaN, or an empty string "") is considered truthy. This means numbers (except 0), non-empty strings, objects, arrays, functions, and even some quirky values like "0" are all truthy.
Here’s a detailed look at the most common truthy values in JavaScript:
Any number, whether positive or negative, is truthy.
This is truthy! This is also truthy!
Any string with at least one character is truthy, including strings containing whitespace.
Non-empty strings are truthy! Even whitespace is truthy!
All objects (including empty objects {}) are truthy.
An empty object is truthy! Objects with properties are truthy!
Similarly, all arrays (including empty arrays []) are truthy.
An empty array is truthy! Non-empty arrays are truthy!
Functions are always truthy, even if they do nothing.
Functions are truthy!
All JavaScript Date objects are truthy, regardless of their validity.
Dates are truthy!
All BigInt values, except 0n, are truthy.
BigInt is truthy!
All Symbol values are truthy.
Symbols are truthy!
To better understand how truthy values work in JavaScript, Let's see an example
1 is truthy.
-1 is truthy.
hello is truthy.
is truthy.
[object Object] is truthy.
is truthy.
function () { } is truthy.
Mon Dec 09 2024 08:00:36 GMT+0000 (Coordinated Universal Time) is truthy.
Sym...Understanding truthy values helps you write concise and readable code. For example:
Providing default values
Guest
Checking for existence
Truthy values in JavaScript include any value that isn’t explicitly falsy. This simple rule makes JavaScript flexible but also requires attention to detail to avoid unexpected behavior. Remember, non-zero numbers, non-empty strings, objects, arrays, functions, symbols, and dates are all truthy—making JavaScript both powerful and occasionally quirky.