
JavaScript Boolean
The JavaScript boolean is a primitive data type that can have only two values: true
or false
. Booleans are used to represent the truth or falsity of an expression or condition in a program.
Boolean values are often used in conditional statements such as if
statements, where the program can take different actions depending on whether a condition evaluates to true
or false
. For example:
let isSunny = true;
if (isSunny) {
console.log("It's a sunny day!");
} else {
console.log("It's not a sunny day.");
}
In the example above, the isSunny
variable is a boolean value that is set to true
. The if
statement checks if the value of isSunny
is true
, and if so, it logs the message “It’s a sunny day!” to the console. If the value of isSunny
is false
, it logs the message “It’s not a sunny day.” to the console instead.
In addition to being used in conditional statements, booleans can also be used in logical operations such as &&
(AND) and ||
(OR) to combine multiple boolean values and determine the final result. For example:
let isSunny = true;
let isWarm = false;
if (isSunny && !isWarm) {
console.log("It's a sunny but cool day.");
} else if (isSunny || isWarm) {
console.log("It's either sunny or warm (or both).");
} else {
console.log("It's not sunny or warm.");
}
In the example above, the if
statement checks if it’s sunny and not warm, and logs the message “It’s a sunny but cool day.” to the console if so. If it’s either sunny or warm (or both), it logs the message “It’s either sunny or warm (or both).” to the console. Otherwise, it logs the message “It’s not sunny or warm.” to the console.