DEV Community

Keerthana Krishnan
Keerthana Krishnan

Posted on

You're using && and || incorrectly

Let's look at some expressions

const a = 1 || 0 // a = 1
const b = 0 || 2 || 1 // b = 2
const c = 0 || false || null || '' // c = ''
const d = 1 && 2 && 3 // d = 3
const e = 2 && "" && 3 // e = ""

If you evaluated all of these expressions correctly, then congratulations! You do need this article, go forth ye wise developer. However, if you're confused why these expressions didn't evaluate to a Boolean value, read on!

These operators evaluate and return the logical value when evaluated from left to right. This returned value is always one of the operands so if the operators are used on non-boolen values, it will return a non-boolean value

JavaScript has 6 falsy values -

  1. false
  2. 0
  3. "" or ''
  4. null
  5. undefined
  6. NaN

If a value is not falsy, it's truthy

The || operator returns the first truthy value and if none are truthy, it returns the last value (which is falsy)

The && operator returns the first falsy value and if none are falsy, it returns the last value (which is truthy)

With this perspective, go through the expressions above and see if you get the right answers this time :)

How can you use this?

When you use these operators, be sure that the operands used are actually boolean values to avoid truthy/ falsy values.

While you could use them inside an if() while() or a ?: this is still risky, if your operands are not boolean. However, the bigger problem arises when they are evaluated into a variable.

For example, [] or {} are truthy values even though they are empty. So,

const m = [1,2,3,4,5]
const n = m.filter(i => i > 100) // n = []
const o = n.length // o = 0
const p = (n && o) // p = 0

Here if p is used in an if() or a ?: it will evaluate to falsy but if you use p with the assumption that it's is a Boolean somewhere else, Ex: typeof y === 'boolean' that will be false

A very simple fix is using Boolean() Ex:
const q = Boolean(n && o) // q = false

Conclusion

  • && and || are logical operators which return one of the operands, not necessarily a boolean value
  • Be careful to avoid truthy/ falsy values when evaluating expressions with && or ||
  • Wrap your expressions inside a Boolean() to always return a boolean result

Enjoy this article? Follow me to read more interesting articles on JS, React and more!

Top comments (0)