JavaScript Booleans

In JavaScript, a Boolean is a primitive data type that represents one of two values: true or false. Booleans are often used in conditional testing to control the flow of a program.

1. Boolean Values

  • The two possible values of a Boolean type are:
    • true
    • false
      let isJavaScriptFun = true;
      let isItRaining = false;
      

      Try It Now

2. Boolean as a Result of Comparisons

Boolean values are often returned as a result of comparison operations.

console.log(5 > 3);   // true
console.log(5 === 3); // false

Try It Now

3. Using Boolean in Conditional Statements

Booleans are used in conditional statements like if and else.

let age = 20;

if (age >= 18) {
  console.log('You are an adult.');
} else {
  console.log('You are not an adult.');
}

Try It Now

4. Boolean Functions

JavaScript provides the Boolean() function to convert other types to Boolean.

console.log(Boolean(1));    // true
console.log(Boolean(0));    // false
console.log(Boolean(''));   // false
console.log(Boolean('Hi')); // true

Try It Now

5. Truthy and Falsy Values

In JavaScript, certain values are considered truthy or falsy. A truthy value evaluates to true in a Boolean context, while a falsy value evaluates to false.

Falsy Values:

  • false
  • 0
  • -0
  • 0n (BigInt zero)
  • "" (empty string)
  • null
  • undefined
  • NaN

Truthy Values:

  • Any value that is not falsy.
  • Examples: true, any non-zero number, non-empty string, arrays, objects.
if (1) {
  console.log('This is truthy'); // This will execute
}

if (0) {
  console.log('This is falsy'); // This will not execute
}

Try It Now

6. Boolean Object

The Boolean object is a wrapper around the Boolean primitive. It is rarely used in practice, as it behaves differently from Boolean primitives.

let x = new Boolean(false);
console.log(typeof x); // "object"

Try It Now

Using Boolean as an object is generally discouraged as it can lead to unexpected results.

let y = new Boolean(false);
if (y) {
  console.log('This will run because objects are truthy');
}

Try It Now

7. Boolean in Logical Operations

Booleans are commonly used in logical operations, such as && (AND), || (OR), and ! (NOT).

  • AND (&&): Returns true if both operands are truthy.
  • OR (||): Returns true if at least one operand is truthy.
  • NOT (!): Inverts the truthiness of a value.
console.log(true && false); // false
console.log(true || false); // true
console.log(!true);         // false

Try It Now

Summary

  • Booleans are essential in controlling the flow of programs through conditions and loops.
  • Use the Boolean() function to convert values to Boolean.
  • Be aware of truthy and falsy values when writing conditional logic.
  • Prefer using Boolean primitives over Boolean objects to avoid unexpected behavior.