In web programming, Booleans are an essential part. In Javascript, boolean values are used to represent true or false.
We can declare and assign boolean values using the keywords true or false.
var isTrue = true;
var isFalse = false;
In Javascript, boolean values can be used in conditional expressions to check and determine the program's flow.
Javascript provides logical operators to work with boolean values. Here are some common logical operators:
NOT operator (!): Inverts the boolean value.
var isTrue = true;
var isFalse = !isTrue; // false
AND operator (&&): Returns true if both expressions are true.
var isTrue = true;
var isFalse = false;
var result = isTrue && isFalse; // false
OR operator (||): Returns true if at least one of the expressions is true.
var isTrue = true;
var isFalse = false;
var result = isTrue || isFalse; // true
To compare boolean values, we can use comparison operators such as ==, ===, !=, !==, >, <, >=, and <=.
var isTrue = true;
var isFalse = false;
console.log(isTrue == true); // true
console.log(isTrue === true); // true
console.log(isFalse != true); // true
console.log(isFalse !== true); // true
Boolean values are often used in conditional expressions to check and determine the program's flow.
var age = 18;
if (age >= 18) {
console.log("Bạn đã đủ tuổi để lái xe.");
} else {
console.log("Bạn chưa đủ tuổi để lái xe.");
}
Boolean values can also be used to control loop flow. Here is an example using a while loop:
var count = 0;
var isLimitReached = false;
while (!isLimitReached) {
count++;
console.log("Số lượt: " + count);
if (count === 10) {
isLimitReached = true;
}
}