The three logical operators of Javascript are NOT(!), AND(&&), and OR(||). These three logical operators allow you to combine Boolean expressions or negate them.
First, we will go over the NOT(!) operator (which is also called the bang operator). In essence, if a variable (let's say x) is a truthy value, then !x will return as false. The inverse is also applicable, where if x is already falsey, then !x ends up returning as true.
The second logical operator we will go over is AND(&&). It takes two expressions and will always return one of the two expressions. If the first expression is falsey, the AND(&&) operator will return the value of the first expression, but if the first expression is truthy, it will return the value of the second operation. It's important to note that if the first expression is falsey, the AND(&&) operator will return the first expression's value and stop there, without checking the second expression. However, if both expressions return truthy values, the return value will always be from the second expression.The first example below shows the AND(&&) operator in action with returning only the value of the first expression as it is falsey. The second example below shows the AND(&&) operator returning the value of the second operation as the first operation is truthy.
The 3rd logical operator is the OR(||) operator. Like the AND(&&) operator, it also takes two expressions and will always return the value of one of the two expressions. Think of it as the inverse of the AND(&&) operator. If the first expression is truthy, then the value of the first expression is returned and the second expression is never looked at. If the first expression is falsey, then the value of the second expression is returned. However, if both expressions return falsey values, the return value will always be from the second expression. The first example below shows the OR(||) operator in action with returning only the value of the first expression as it is truthy. The second example below shows the OR(||) operator returning the value of the second operation as the first operation is falsey.
These three logical operators can ultimately be combined with the equality and relational operators to create expressions that are much more complicated. Below is an example of an if else statement that utilizes equality, relational, and logical operators. In this case, the first expression was falsey as 7*2 = 14, which is not 15, so the second expression was evaluated. As 14 is greater than 7, the if statement returned a console.log of "Correct!". If the second expression was instead 14 > 15, then "Wrong!" would have been console logged.
Top comments (0)