You already know numeric and string variables, but programming requires more. In this topic, we will discuss another important variable type and the operators working with it.
Boolean type
There are statements about which we can say whether they are true. It is raining today, so the statement it is raining is true. The statement 5 < 3 is always false, and the Moon orbits the Earth is true. These statements have a particular type – logical or boolean.
There are only two possible values of boolean variables: true and false. Look at the example of setting a boolean variable and printing it:
let bool = true;
console.log(bool); // trueLogical operators
Logical operators are used to perform operations with boolean variables. There are only three of them in JavaScript: logical AND (&&), logical OR (||), and NOT (!). The first two operators are binary, which means that they're used with two operands. The ! operator is unary, so it only takes one operand. && returns true if both operands are true and false in all other cases:
console.log(true && true); // true
console.log(true && false); // false
console.log(false && true); // false
console.log(false && false); // false|| returns false if both operands are false and true in all other cases:
console.log(true || true); // true
console.log(true || false); // true
console.log(false || true); // true
console.log(false || false); // false! changes false to true and vice versa:
console.log(!false); // true
console.log(!true); // false
console.log(!!true); // trueMore capabilities of logical operators in JS
Logical operators in JavaScript have much broader capabilities than the traditional usage described above. Their operands can not only be boolean variables but also variables of other types.
Among the numerical values, 0 is considered false, and all other numbers are true. As for strings: all strings except the empty one are considered true.
Expressions are always calculated from left to right. && returns false as soon as it finds the first occurring false, and the operator || returns true as soon as it sees the first true. More generally, && returns the first value that is considered false, and || returns the first value that is treated as true.
console.log(true || 0); // true
console.log(false && "sun"); // false
console.log(1 || 0); // 1Priority
When working with complex expressions, you should take into account their priority. The priority of ! is higher than that of &&, and the priority of && is higher than that of ||. If you need to change the priority, use parentheses:
console.log(!false && !true); // false
console.log(!(false && !true)); // trueConclusion
In this topic, we have learned about booleans and reviewed three logical operators in JavaScript. We have also discovered that JavaScript's logical operators can be used with variables that are not just logical. It is now time to put this knowledge into practice.