Skip to main content

Understanding JavaScript Booleans

By SamK
0
0 recommends
Category(s)
Topic(s)

In this tutorial, you'll learn about JavaScript Booleans.

Understanding JavaScript Booleans

A JavaScript Boolean represents one of two possible values: true or false.

Boolean Values in Programming

In many programming situations, you need a data type that can hold only one of two values, such as:

  • YES / NO
  • ON / OFF
  • TRUE / FALSE

JavaScript provides the Boolean data type for such cases, which can store only true or false values.

The Boolean() Function

The Boolean() function is used to determine if an expression or a variable evaluates to true or false.

Example:

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

A simpler way to check the Boolean value of an expression is:

console.log(10 > 9); // true

Comparisons and Conditions

Booleans are widely used in JavaScript comparisons and conditional statements.

  • ==: Equal to: if (day == "Monday")
  • >: Greater than: if (salary > 9000)
  • <: Less than: if (age < 18)

The Boolean value of an expression determines the result of all JavaScript comparisons and conditions.

Truthy and Falsy Values in JavaScript

Everything with a "value" is true

The following values always return true when evaluated as a Boolean:

console.log(Boolean(100));      // true
console.log(Boolean(3.14));     // true
console.log(Boolean(-15));      // true
console.log(Boolean("Hello")); // true
console.log(Boolean("false")); // true
console.log(Boolean(7 + 1 + 3.14)); // true

Everything without a "value" is false

The following values always return false:

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

JavaScript Booleans as Objects

JavaScript booleans are usually primitive values created using literals:

let x = false;
console.log(typeof x); // boolean

However, booleans can also be created as objects using the new keyword:

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

Warning: Avoid Using Boolean Objects

It is not recommended to create Boolean objects using new because:

  • They slow down execution speed.
  • They may lead to unexpected results.

Example of Unexpected Results:

let x = false;
let y = new Boolean(false);
console.log(x == y);  // true (due to type coercion)
console.log(x === y); // false (different types)

Two Boolean objects are never equal, even if their values are the same:

let a = new Boolean(false);
let b = new Boolean(false);
console.log(a == b);  // false
console.log(a === b); // false

Questions & Answers