Course

JavaScript Boolean: True and False in JS

In JavaScript, a boolean is a fundamental data type for conditional logic and other logical operations. Booleans can have two values: true and false.

How to Use Booleans in JavaScript

Using true and false in JavaScript is straightforward. You can assign them to a variable or get them as a result of comparisons and logical operations. Use the syntax to declare boolean values using let, var, or const, depending on whether the value needs to be reassigned.

jsx
let isAuthenticated = false; let isGreaterThanFive = (10 > 5); // evaluates to true

When to Use Booleans in JavaScript

Booleans are essential when you need to make decisions in your code. Here are some common scenarios where booleans in JavaScript are particularly useful:

Conditional Statements

Conditional statements like if statements rely heavily on boolean values to determine which code block to execute.

jsx
let userHasAccess = false; if (userHasAccess) { console.log("Access granted."); } else { console.log("Access denied."); // This line executes }

While Loops

In while loops, a boolean condition controls how long the loop will continue to run.

jsx
let counter = 3; while (counter > 0) { console.log(counter); counter--; // Decrements counter until the condition is false }

Examples of Booleans in JavaScript

Here are some simplified examples to illustrate the common use cases of booleans in JavaScript:

Registration Forms

In an HTML registration form, booleans might verify whether the inputs in a form meet certain criteria.

jsx
let formIsValid = false; let age = 20; if (age >= 18) { formIsValid = true; } console.log("Form valid:", formIsValid); // Output: Form valid: true

Feature Toggles

Feature toggles are a common use case where booleans control the activation of certain features in an application.

jsx
let featureEnabled = true; if (featureEnabled) { console.log("New feature is live."); }

Booleans can also be used to dynamically apply CSS styles to elements based on conditions.

jsx
const isDarkMode = true; document.body.style.backgroundColor = isDarkMode ? "black" : "white"; // Change CSS based on boolean value

Learn More About the Boolean Data Type in JavaScript

Truthy and Falsy Values

Besides true and false, other data types can behave as booleans in boolean contexts like conditions.

“Truthy” values behave like true, while “falsy” values behave like false. The six false values in JavaScript are 0, "" (empty string), NaN, null, undefined, and false. Any other value is truthy, i.e. resolves to true.

jsx
let name = "" if (name) { console.log(`Hello, ${name}!`); } else { console.log("Please provide a name."); }

Logical Operators in JavaScript

In JavaScript, logical operators are essential for advanced boolean logic. The primary logical operators are && (and), || (or), and ! (not). The && and || operators evaluate expressions from left to right and return the first operand that determines the outcome.

The && operator only returns true if the expressions on its left and right are both true. If the first expression is false, the logical and “short-circuits” to return false without evaluating the second expression.

jsx
let a = true, b = false; let result = a && b; // Outputs: false, because b is false let bothTrue = true && true; // Outputs: true

The || operator returns true if at least one of the expressions is true. The logical or also uses short-circuiting. If the first expression is true, || returns true without evaluating the second expression.

jsx
let c = false, d = true; let anotherResult = c || d; // Outputs: true, because d is true let bothFalse = false || false; // Outputs: false

The ! operator inverts the truth value of a boolean expression. When an expression is true, the logical not turns it into false and vice versa.

jsx
let e = true; let notTrue = !e; // Outputs: false let f = false; let notFalse = !f; // Outputs: true

Boolean expressions often involve comparison operators like ==, ===, <, and >=.

jsx
let age = 18; console.log(age >= 18); // true, using a comparison operator console.log(age === "18"); // false, strict equality check

The Boolean Function in JavaScript

The Boolean() function in JavaScript takes any value as a parameter and converts it to a boolean. If the value is one of the six falsy values (0, "", NaN, null, undefined, and false), the function returns false. For any other values, including arrays and objects, Boolean() returns true.

jsx
console.log(Boolean(0)); // false console.log(Boolean('')); // false console.log(Boolean('JavaScript')); // true console.log(Boolean({})); // true console.log(Boolean(undefined)); // false

Boolean values often appear in JSON data when representing true/false conditions.

jsx
const userData = { name: "Alice", emailVerified: true, // Boolean in a JSON object premiumUser: false };

Booleans exist in most programming languages, but JavaScript’s loose type coercion allows values to behave as booleans in certain contexts.

jsx
console.log(Boolean([])); // true (empty array is truthy) console.log(Boolean(null)); // false (null is falsy)

Unlike Python, where booleans are subclasses of integers (True equals 1, False equals 0), JavaScript treats true and false as distinct boolean values.

jsx
# Python Boolean behavior print(True + 1) # Output: 2 print(False + 1) # Output: 1

Boolean Objects in JavaScript

In JavaScript, apart from the primitive boolean values true and false, there is also a Boolean object. The Boolean object is a wrapper around the boolean data type, offering some additional functionality.

You can create Boolean objects using the new Boolean() constructor. This might seem similar to the Boolean() function, but it behaves quite differently. The Boolean() function returns a primitive value of type boolean. The new Boolean() constructor, on the other hand, creates an object of the Boolean class.

jsx
let booleanObject = new Boolean(true); let booleanValue = Boolean(true); console.log(booleanObject); // Outputs: [Boolean: true] console.log(booleanValue); // Outputs: true

Using Boolean objects usually adds complexity without providing benefits. For almost any purpose, the primitive boolean values true and false are sufficient.

In JavaScript, a boolean primitive is a simple true/false value, while the Boolean object is a wrapper around a boolean.

jsx
let primitiveBool = true; // Boolean primitive let objectBool = new Boolean(true); // Boolean object console.log(typeof primitiveBool); // 'boolean' console.log(typeof objectBool); // 'object'