JAVASCRIPT

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.

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.

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.

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 a registration form, booleans might verify whether the inputs in a form meet certain criteria.

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.

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

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 falsy values in JavaScript are 0, "" (empty string), NaN, null, undefined, and false. Any other value is truthy, i.e. resolves to true.

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 && 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.

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.

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.

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

The Boolean Function in JavaScript

The Boolean() function in JavaScript converts any value 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.

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

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.

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.

Learn JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH