Logical Operators in JavaScript

Natalia Wit
2 min readAug 16, 2020

JavaScript’s three logical operators: NOT (!), AND (&&), and OR (||).

Logical Operators

A logical operator is a symbol or word used to connect two or more expressions. There are three logical operators in JavaScript: || (OR), && (AND), ! (NOT). Although they are called “logical”, they can be applied to values of any type, not only boolean. Their result can also be of any type.

1.! NOT

This logical NOT operator (!), also called the bang operator, operates on an expression. It returns the opposite of the expression’s truthiness. For example if a = true then !a will returnfalse , else if a = false then !a will returntrue.

2. !!

You can also convert an expression to a Boolean using !!. As a shorter to convert any value into a boolean, we can just use the two NOT operators from above.

a = "this is truthy"

!a => //returns false

!!a => //returns true

Reading from left to right, the JavaScript engine will see the ! and turn to the right to see what we are asking to invert. The engine resolves the variable a to "this is truthy. Then it sees the first ! and inverts the variable to return false. Right now seeing!!a,we’re no longer see the variable but we’re looking at !false which will return the opposite => true.

3. && AND

The logical AND operator (&&) takes two expressions.

expression1 && expression2

The return value of the && operator is always one of the two expressions. If the first expression is false, the AND operator returns the value of the first expression. If the first expression is truthy then the AND operator will return the second expression.

  • *NOTE — if the first expression is false the && operator will return the first expression without ever checking the second expression.
  • If both expressions are truthy then the engine will check the first expression and then follow with second and return the second expression.

4. OR

The logical OR|| also takes in two expressions. The return value of the || operator is always one of the two expressions. If the first expression is true the OR operator returns the value of the first expression. If the first expression is false then the OR operator will return the second expression.

  • **NOTE — If the first expression is true, then the value is immediately returned and the second expression is never even evaluated
  • If the first expression is false, then the OR operator returns whatever the second expression evaluates to

Conclusion

The best way to understand the concepts is to play around with the operators in the console itself. The logical operators in JavaScript are very powerful. Once you understand how to use them correctly, they are MAGIC!

--

--