DEV Community

Cover image for Let's Talk Logical Operators
Katelyn
Katelyn

Posted on

Let's Talk Logical Operators

We're going to go over three of the logical operators that Javascript uses:

truthy operator values

Why use a logical operator?

The benefit of a logical operator is to connect two (or more!) expressions so that the value of the total (all of the expressions you just connected) is dependent on those expressions.

These operators are used within code to compare variables and values when creating various logic methods, often using their boolean values. When used within functions it gives more logic options for the code to use and change based on user behavior. This can also help DRY up code in condensing functions.

! (NOT)

The NOT ! operator is generally used as a boolean. Logical NOT will have truthy value if the operator it's called on (like !(6 === 3) is false and vice-versa (like !(6 === 6) is considered a false value. Here's a different way of wording the NOT operator with the previous examples: Return true if x is not strictly equal to y, otherwise return false.

Logical Operators

&& (AND)

The AND && operator will return true if both sides of the operator or boolean values are true ((x < 10 && y > 1) is true) otherwise, it returns false. In other words, when using the AND operator, if both x and y are true, then the logic as a whole is true. If one part of the logic is false, the whole problem returns false. It's also important to not that you can chain on the AND operator more than once.

AND Operator

|| (OR)

As with the other operators, the OR || operator is usually used within a boolean context. A problem using the OR operator will return true if either side of the values are true. If either/both x or y are true, return true. If both are false, return false. It's also important to not that you can chain on the OR operator more than once.

OR Operator

What if you mix operators?

Operators can be mixed within one expression. However, logical operators use an order of precedence, called logical operator precedence if that occurs. The order is as follows: logical NOT (!), logical AND (&&), then logical OR (||)

example

TL;DR

  • NOT ! - this will negate a boolean value (!is = is not)
  • AND && - can be used with two (or more) values and will return true if all values are also true, will return false otherwise
  • OR || - can also be used with two (or more) values and will return if any of the values are true, will return false if all of the values are false
  • if you use these operators in the same expression, keep in mind the order in which Javascript will go through them.

Top comments (0)