Introduction to JavaScript booleans
Summary
This article explains how booleans work in JavaScript, covering primitive true/false values, explicit vs. implicit coercion, truthy/falsy rules, and common pitfalls. It also highlights best practices and edge cases to avoid when working with boolean logic.
Introduction #
In JavaScript, booleans are a primitive data type that represent one of two possible values: true or false. These values are often used to control the flow of programs through conditionals, loops, and logical operations.
What is a boolean? #
A boolean is a data type with only two possible values. In JavaScript, you can directly assign a boolean in a variable:
var isOpen = true;
var isClosed = false;
Booleans are typically the result of comparisons, conditionals, or boolean coercion.
Check the truthiness of a value using Boolean() #
JavaScript provides the global Boolean() function to convert any value to its boolean equivalent. This is helpful when you want to explicitly determine whether a value is truthy or falsy.
console.log(Boolean(123)); // true
console.log(Boolean("")); // false
console.log(Boolean(undefined)); // false
Boolean coercion #
Boolean coercion refers to the implicit conversion of a value to true or false in a context that expects a boolean, such as an if statement.
JavaScript evaluates some values as falsy and everything else as truthy.
False #
| Value | Result | Explanation |
|---|---|---|
null | false | Represents the intentional absence of any value. |
undefined | false | A variable that has not been assigned a value. |
false | false | Literal boolean false. |
0 | false | Numeric zero. |
-0 | false | Negative zero, treated the same as zero. |
0n | false | BigInt zero. |
NaN | false | Not-a-Number is considered falsy. |
"" | false | An empty string. |
True #
| Value | Result | Explanation |
|---|---|---|
true | true | Literal boolean true. |
"0" | true | Non-empty string is always truthy. |
[] | true | Empty array is still an object and is truthy. |
{} | true | Empty object is also truthy. |
Symbol() | true | Symbols are always truthy. |
function(){} | true | Functions are objects and thus truthy. |
Examples of boolean coercion #
Undefined variable #
If a variable is declared but not assigned a value, it is undefined, which is falsy.
var foo;
console.log(Boolean(foo));
Result: false
Empty string #
An empty string evaluates to false in boolean contexts.
var message = "";
console.log(Boolean(message));
Result: false
Number zero #
Zero is a falsy value in JavaScript.
var count = 0;
console.log(Boolean(count));
Result: false
Non-zero number #
Any non-zero number is truthy, including negative numbers.
var count = -7;
console.log(Boolean(count));
Result: true
Null value #
null is used to indicate the intentional absence of a value and is falsy.
var value = null;
console.log(Boolean(value));
Result: false
Non-empty array #
Even an empty array is treated as truthy.
var items = [];
console.log(Boolean(items));
Result: true
Non-empty object #
Objects, even when empty, are truthy.
var user = {};
console.log(Boolean(user));
Result: true
Using Boolean() to test values #
The Boolean() function is a straightforward way to test truthiness in JavaScript.
console.log(Boolean("JavaScript")); // true
console.log(Boolean(0)); // false
Result: true, false
Explicit vs. implicit boolean coercion #
In JavaScript, boolean coercion can happen in two ways: explicitly (where you intentionally convert a value to a boolean) or implicitly (where JavaScript automatically converts a value in a boolean context).
Explicit coercion #
Explicit coercion occurs when you deliberately convert a value to a boolean using:
- The
Boolean()function. - The double negation (
!!) shorthand.
console.log(Boolean("hello")); // true (explicit)
console.log(!!0); // false (explicit)
This method is clear and preferred when you need to ensure a value is treated strictly as true or false.
Implicit coercion #
Implicit coercion happens automatically in logical contexts, such as:
ifconditionswhileloops- Logical operators (
&&,||,!)
if ("hello") {
console.log("Runs because 'hello' is truthy.");
}
let result = 0 || "default"; // "default" (implicitly coerces 0 to false)
When to Use Which?
- Use explicit coercion when clarity is important (
Boolean(x)or!!x). - Use implicit coercion for concise conditionals (
if (x)).
Common pitfalls #
While boolean coercion is useful, some behaviors can be unintuitive. Here are common pitfalls to avoid:
Objects and arrays are always truthy #
Even empty objects ({}) and arrays ([]) are truthy, which can be surprising:
if ([]) {
console.log("This runs."); // Array is truthy
}
console.log(Boolean({})); // true
Workaround: Check length (for arrays) or keys (for objects) explicitly:
if (arr.length) { ... }
if (Object.keys(obj).length) { ... }
"0" and "false" are truthy #
Non-empty strings, even those containing "0" or "false", are truthy:
console.log(Boolean("0")); // true
console.log(Boolean("false")); // true
Workaround: Compare against "0" or parse strings if needed:
if (str !== "0") { ... }
new Boolean() objects are truthy #
Creating a boolean with new Boolean(false) returns an object, which is always truthy:
let boolObj = new Boolean(false);
if (boolObj) {
console.log("This runs!"); // Surprise!
}
Fix: Always use primitive booleans (true/false) instead.
NaN is falsy, but so are other numbers #
NaN is falsy, but so is 0—leading to potential confusion in numeric checks:
console.log(Boolean(NaN)); // false
console.log(Boolean(0)); // false
Workaround: Use isNaN() for NaN checks and explicit comparisons for 0:
if (x !== 0) { ... }
if (isNaN(x)) { ... }
null vs. undefined in conditionals #
Both are falsy, but they represent different concepts:
null→ Intentional absence of value.undefined→ Uninitialized variable.
console.log(Boolean(null)); // false
console.log(Boolean(undefined)); // false
Workaround: Distinguish them with strict equality (===):
if (x === null) { ... }
Booleans as objects #
While true and false are primitive values, JavaScript also allows the creation of Boolean objects using the new Boolean() constructor. These objects behave differently from primitive booleans in conditional statements.
var boolObj = new Boolean(false);
if (boolObj) {
console.log("This runs.");
}
Result: This runs.
This is because objects are always truthy, even if the value they hold is false.
Boolean objects are almost never useful in practice and can lead to confusing behavior. Primitive booleans are preferred.
FAQ's #
Most common questions and brief, easy-to-understand answers on the topic:
What is a boolean in JavaScript?
A boolean in JavaScript is a data type that represents one of two values: true or false.
How can I convert a value to a boolean?
You can convert a value to a boolean using the Boolean() function or the double NOT operator (!!).
Is an empty string falsy in JavaScript?
Yes, an empty string ('') is evaluated as false in a boolean context.
Are objects always truthy in JavaScript?
Yes, all objects are considered truthy, even empty ones like {} or [].
What is boolean coercion?
Boolean coercion is the automatic conversion of a value to true or false when used in a boolean context.
Further readings #
Sources and recommended, further resources on the topic:
- MDN Web Docs: Boolean Type
- MDN Web Docs: Boolean values
- ECMAScript Specification: Boolean Type
- Introdution to JavaScript variables
License
Introduction to JavaScript booleans by Jonas Jared Jacek is licensed under CC BY-SA 4.0.
This license requires that reusers give credit to the creator. It allows reusers to distribute, remix, adapt, and build upon the material in any medium or format, for noncommercial purposes only. To give credit, provide a link back to the original source, the author, and the license e.g. like this:
<p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://www.ditig.com/javascript-booleans">Introduction to JavaScript booleans</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://www.j15k.com/">Jonas Jared Jacek</a> is licensed under <a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank" rel="license noopener noreferrer">CC BY-SA 4.0</a>.</p>For more information see the Ditig legal page.