Boolean Values in JavaScript
Boolean Values in JavaScript — Truthy and Falsy Values
In this article, we will explore Boolean values in JavaScript in detail: how they work, which values are considered truthy or falsy, and how to use them effectively in programming.
The Boolean type in JavaScript has only two possible values:
These two values are used in conditional statements, loops, and other logical operations.
const isLoggedIn = true;
const hasAccess = false;
Truthy vs Falsy Values
In JavaScript, certain values are automatically converted to Booleans when required. These values are called "truthy" or "falsy".
These values are considered equivalent to false in Boolean contexts:
// These values are falsy:
false
0
-0
0n // BigInt zero
"" // empty string
null
undefined
NaN
Example:
if (!0) {
console.log("0 is falsy");
}
All other values are considered truthy, meaning they evaluate to true.
// Examples:
"Hello"
42
[]
{}
function () {}
if ("hello") {
console.log("Strings are truthy");
}
You can explicitly convert a value to a Boolean using the Boolean() function.
Boolean(0); // false
Boolean("text"); // true
Or use the shorthand:
!!value // Double NOT operator to coerce to Boolean
console.log(!!"abc"); // true
console.log(!!null); // false