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
ifstatement will only be executed if the conditionx < yis true, which it is because5is indeed less than10.
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
ifstatement will only be executed if both conditionsx < yandy > 8are 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:
boolean1will betruebecausex < yistrue, andboolean2will be false becausex > yis false.
Booleans are an essential part of programming and are used in many different ways to control the flow and logic of a program.