JavaScript Booleans and Comparison Operators

Learn JavaScript booleans and comparison operators, including equality operators, relational operators, and the difference between truthy and falsy values. Essential concepts for making decisions in your code.

JavaScript Booleans and Comparison Operators

Booleans are one of the most fundamental data types in JavaScript, representing simple true or false values. Understanding how booleans work alongside comparison operators is essential for making decisions in your code and controlling program flow.

What Are JavaScript Booleans?

A boolean is a primitive data type that can only hold one of two values: true or false. These values are keywords in JavaScript and must be written in lowercase.

let isLoggedIn = true;
let hasPermission = false;
let isComplete = true;

console.log(isLoggedIn); // Output: true
console.log(typeof isLoggedIn); // Output: boolean

Booleans are often the result of comparisons or conditions, making them crucial for controlling what your program does next.

Comparison Operators

Comparison operators evaluate relationships between values and always return a boolean result. Let's explore each type:

Equality Operators

JavaScript provides two ways to check equality, and understanding the difference is important:

// Loose equality (==) - compares values with type conversion
console.log(5 == "5");    // Output: true
console.log(true == 1);   // Output: true
console.log(null == undefined); // Output: true

// Strict equality (===) - compares values AND types
console.log(5 === "5");   // Output: false
console.log(true === 1);  // Output: false
console.log(null === undefined); // Output: false

Why use strict equality? Always use strict equality (===) unless you specifically need type conversion. Loose equality can produce unexpected results because JavaScript automatically converts types during comparison. For example, null == undefined returns true due to type coercion, even though they're different types. Strict equality prevents these surprises and makes your code more predictable and easier to debug.

Inequality Operators

Similar to equality, you have loose and strict inequality operators:

// Loose inequality (!=)
console.log(5 != "3");    // Output: true
console.log(5 != "5");    // Output: false

// Strict inequality (!==)
console.log(5 !== "5");   // Output: true
console.log(5 !== 5);     // Output: false

Relational Operators

These operators compare the relative values and are commonly used with numbers:

let score = 85;
let passingGrade = 70;

console.log(score > passingGrade);  // Output: true
console.log(score < 100);           // Output: true
console.log(score >= 85);           // Output: true
console.log(score <= 70);           // Output: false

// Note: This is assignment, not comparison
score = 90;
console.log(score); // Output: 90 (not a boolean)

Truthy and Falsy Values

JavaScript has a concept of "truthiness" where non-boolean values can be evaluated in boolean contexts. This means values can be considered "truthy" (acting like true) or "falsy" (acting like false) when used in conditions, even if they're not actual boolean values.

Falsy values - There are exactly 7 falsy values in JavaScript:

console.log(Boolean(false));     // false
console.log(Boolean(0));         // false
console.log(Boolean(-0));        // false
console.log(Boolean(0n));        // false (BigInt zero)
console.log(Boolean(""));        // false (empty string)
console.log(Boolean(null));      // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN));       // false

Truthy values - Everything else is truthy, including:

console.log(Boolean(1));         // true
console.log(Boolean(-1));        // true (any non-zero number)
console.log(Boolean("hello"));   // true (any non-empty string)
console.log(Boolean("0"));       // true (string with content)
console.log(Boolean("false"));   // true (string with content)
console.log(Boolean([]));        // true (empty array)
console.log(Boolean({}));        // true (empty object)
console.log(Boolean(function(){})); // true (functions)

Practical Examples

Here's how booleans and comparison operators work together in real scenarios:

// User authentication check
let username = "john_doe";
let password = "secret123";

let isValidUser = username.length > 0 && password.length >= 8;
console.log(isValidUser); // Output: true

// Age verification
let userAge = 25;
let canVote = userAge >= 18;
let canRentCar = userAge >= 21;

console.log(`Can vote: ${canVote}`);        // Output: Can vote: true
console.log(`Can rent car: ${canRentCar}`); // Output: Can rent car: true

// Form validation
let email = "[email protected]";
let hasAtSymbol = email.includes("@");
let hasValidLength = email.length > 5;

let isValidEmail = hasAtSymbol && hasValidLength;
console.log(isValidEmail); // Output: true

Common Pitfalls to Avoid

Watch out for these common mistakes when working with booleans and comparisons:

// Don't compare booleans to true/false explicitly
let isActive = true;

// Avoid this:
if (isActive === true) {
    console.log("Active");
}

// Do this instead:
if (isActive) {
    console.log("Active");
}

// Be careful with assignment vs comparison
let score = 85;
console.log(score = 90);  // Output: 90 (assignment, returns assigned value)
console.log(score == 90); // Output: true (comparison, returns boolean)

// Watch out for type coercion surprises
console.log("0" == 0);     // true (string converted to number)
console.log("" == 0);      // true (empty string converted to number)
console.log(false == 0);   // true (boolean converted to number)

// Array and object comparisons can be tricky
console.log([] == []);     // false (different objects in memory)
console.log({} == {});     // false (different objects in memory)

// Null and undefined equality
console.log(null == undefined);  // true (special case in loose equality)
console.log(null === undefined); // false (different types)

These pitfalls occur because JavaScript's loose equality operator (==) performs type conversion, leading to unexpected results. The assignment operator (=) returns the assigned value rather than a boolean, and objects are compared by reference, not by their contents.

What's Next

Now that you understand booleans and comparison operators, you're ready to learn about conditional statements like if, else if, and switch. These constructs use boolean values to control program flow, letting your code make decisions based on different conditions.