Skip to main content

Booleans in JavaScript

Booleans are a primitive data type that represents true or false values.

The two Boolean values are true and false, and they are used to determine the logic of a program.

Booleans are commonly used in conditional statements, where a piece of code is executed only if a certain condition is true.

As an example:

let x = 5;
let y = 10;

if (x < y) {
console.log("x is less than y");
}

In the example above:

  • The code inside the if statement will only be executed if the condition x < y is true, which it is because 5 is indeed less than 10.

Booleans can also be used in logical operators such as && (and), || (or), and ! (not).

As an example:

let x = 5;
let y = 10;

if (x < y && y > 8) {
console.log("x is less than y and y is greater than 8");
}

In the example above:

  • The code inside the if statement will only be executed if both conditions x < y and y > 8 are true.

Booleans can be created explicitly by using the Boolean() function or implicitly through the evaluation of expressions.

As an example:

let x = 5;
let y = 10;

let boolean1 = Boolean(x < y); // true
let boolean2 = x > y; // false

In the example above:

  • boolean1 will be true because x < y is true, and boolean2 will be false because x > y is false.

Booleans are an essential part of programming and are used in many different ways to control the flow and logic of a program.