HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Booleans

A JavaScript Boolean represents one of two values: true or false. Booleans are named after George Boole and are the backbone of computer logic, conditional testing, and decision-making in your code.


The Boolean() Function

You can use the Boolean() function to find out if an expression (or a variable) is true or false.

console.log(Boolean(10 > 9)); // true
console.log(10 > 9);         // true (the simple way)

Truthy and Falsy Values

In JavaScript, every value has an inherent boolean state. When evaluated in a boolean context (like an if statement), values are either "truthy" or "falsy".

Falsy Values

Everything without a "real" value is false. There are only 6 falsy values in JavaScript:

  • 0 (Zero) and -0
  • "" or '' (Empty string)
  • undefined
  • null
  • false
  • NaN (Not a Number)

Truthy Values

Everything else is true, including:

  • Any number other than 0 (e.g., 100, -5)
  • Any non-empty string (e.g., "Hello", "false")
  • Empty Objects {} and Arrays []
  • Functions

Booleans are for Decisions

Booleans are most commonly used in comparative operations. Comparisons return a boolean result that tells JavaScript which path to take.

let age = 18;
let isAdult = (age >= 18); // Evaluates to true

if (isAdult) {
    console.log("You are allowed to enter.");
}
Note: Booleans are a primitive data type. While you can create them as objects using new Boolean(), it is highly discouraged as it can lead to confusing bugs and slower performance.

Comparison vs. Assignment

A very common mistake for beginners is confusing assignment (=) with comparison (== or ===). Binary logic only works with comparisons.

let x = 0;
if (x = 10) { } 
// This is ALWAYS true because it assigns 10 to x, 
// and 10 is a truthy value!

Key Points to Remember

  • A Boolean value is either true or false
  • Comparisons (>, <, ===) return boolean results
  • Falsy values include 0, "", null, undefined, and NaN
  • Anything with a real value is truthy
  • Always use comparisons, never assignments, inside control statements like if