Search justacoding.blog. [Enter] to search. Click anywhere to close.

October 10th, 2021

JavaScript ||, Or The “Or” Operator – A Guide

In this guide, we’ll go over what the JavaScript || operator actually is, and what exactly it does.

As is common when working in JavaScript in general, there are some quirks and pitfalls to be aware of when using this operator.

We’ll cover each of those cases during this explanation.re

Let’s get right into it!

What the || operator does in JavaScript

In JavaScript, the or operator looks like this: ||.

For this reason, it is also commonly referred to by the name the double pipe operator. Also, more verbosely, the logical “or” operator.

We can use the JavaScript or operator to determine if at least one of the operands in an expression is true:

console.log(true || true) // true
console.log(true || false) // true
console.log(false || false) // false

So that’s fairly straightforward.

The operands in the expression are each evaluated, if at least one of the operands is (or evaluates to) true, our expression will return true also. If not, the expression will return false.

In the example above, we’re only using boolean values (either true or false). This obviously makes the output of our expressions fairly clear and predictable.

However, what happens when one or more of the operands is not a boolean? There are some nuances to consider in this case.

Let’s take a look.

Using the JavaScript || operator when not all values are of boolean type

When one or more of the values in the expression is not a boolean, the behaviour appears to be a little different.

Consider this example:

console.log(false || "some string")

So we’re including both a boolean and and a string in our expression this time. What would you expect the result of this statement to be?

If you said true, you’d be incorrect. If you said false, you’d also be incorrect. That’s because the result is not actually a boolean at all. In fact, this expression above will return some string.

To delve into why exactly this is the case when using the JavaScript or operator, firstly, we’ll need to briefly cover the concept of truthy and falsy values in JavaScript.

Truthy and falsy values in JavaScript

As JavaScript is loosely typed, it makes implicit conversions to boolean values in scenarios such as the ones in this article. So when using the or operator.

It does this by considering non-boolean values to be either truthy or falsy.

If you aren’t familiar, the concept or truthy or falsy values may seem a little strange. However, a lack of understanding with regards to this concept is a common pitfall for JavaScript developers!

So it’s a good idea to get to grips with this stuff.

Let’s start by looking at the falsy values.

JavaScript’s falsy values

JavaScript falsy values are values that would be evaluated to be false when considered under the Boolean context.

Here’s a list of JavaScript’s falsy values for your consideration:

  • false
  • null
  • undefined
  • 0
  • NaN
  • '', ""
  • document.all
  • 0n
  • -0

If the operand doesn’t fall within one of these falsy values; it’s considered to be a truthy value instead.

These JavaScript truthy values would include (but are by no means be limited to) the following:

  • (() => {})
  • "any string that's not empty"
  • -1
  • 1

And so on.

All of those values are to be considered truthy in the boolean context. This includes when they are encountered in expressions using the JavaScript or operator itself.

How can I check if a value is truthy or falsy?

A quick way to check if a value is truthy or falsy in JavaScript is to simply do this within the console (or alternatively console.log it, instead):

!!false // false (unsurprisingly :))
!!-1 // true
!!0 // false
!!null // false
!!"good morning" // true
!!"" // false

By prepending !! before our variable or value, JavaScript will coerce it into a boolean. Truthy values will be coerced to true; falsy values will be coerced to false — as demonstrated above.

We’ll speak more on this topic a bit later on.

Back to the JavaScript || operator…

With those truthy and falsy values in mind, let’s revise our understanding of the or operator to as follows:

JavaScript converts (or coerces) each operand in the expression to be either true or false. If any of the operands are truthy, the first of these values will be returned. If none of the operands are truthy, expect the last (falsy) value to be returned instead.

This means that our expressions won’t actually always return true or false specifically (as would be implied by the initial boolean examples above).

In our initial boolean examples above, we always received a boolean result because the expressions always return the value of one of their operands.

So if we’re operating on only boolean values, we’d always expect a boolean result to be returned.

If our expression is composed from non-boolean values (or a mixture of boolean and and non-boolean), you’ll see that it’s possible to receive a non-boolean result. As stated, it all depends on the type of operands we are using.

Let’s look at some examples of this.

Further examples

None of the values in our expression are truthy, so the last falsy value (-0) is returned:

console.log(0 || -0) // -0

Similarly, there are no truthy operands in this expression either. An empty string ("") is returned now as it’s the last operand in the expression:

console.log(-0 || "") // ""

Let’s expand on that example, and look at an expression with more than 2 operands:

console.log(-0 || "" || false) // false

As expected, false is the result of this expression. All operands are falsy, but false is the very last one.

Now let’s mix in some truthy operands:

console.log(false || false || "something" || false) // something

In this case, something is not a falsy value – it’s truthy. So despite it’s position with regards to the other operands, something will be returned now.

Here’s one final example:

console.log(false || 0 || -0 || "yep" || NaN || "another string" || "") // yep

The string yep is returned as it’s the first truthy value within our expression. another string is also truthy, but yep comes beforehand.

To briefly summarise the JavaScript || operator

As per our examples, you can see that expressions using the JavaScript || operator are firstly coerced to their relevant boolean values; then the first truthy value is returned.

If there are no truthy values, the last falsy value is returned instead.

Using JavaScript type coercion

There are, of course, situations where you may want to only ever receive a boolean return value as part of your expression.

For these cases, we can use type coercion. Specifically, we can do this:

console.log(!!(false || "hello")) // true

By preprending the statement with !!, we’re doing two things:

  • Coercing the value (in this case, “hello”) to a boolean – this is what the first ! is doing
  • Inverting this value, this is what the second ! is doing

So the output of the above is true because we’re coercing the string (“hello”) to a boolean (which is initially false) and then inverting this value to return true.

In general, if you know you may not be dealing specifically with boolean values as part of these kind of expressions, you should use !! to ensure you’ll always receive a boolean result regardless. It’s too easy to be caught out by some of the intricacies of the JavaScript or operator, otherwise!

Practical usages of the JavaScript || operator, using type coercion vs not using type coercion

So as we’ve covered, expressions utilizing the JavaScript || operator will naturally return a value from within the initial selection of operands.

There are cases where we’d want this behaviour, but also cases where we simply want a true or a false return value.

Let’s take a look at some of the practical use cases.

Looking for at least one true value amongst the operands

This is arguably the “intended” use of the || operator, to simply evaluate multiple different booleans at once as per the application’s requirement:

const isRegistered = false
const skippedRegistration = true

console.log(isRegistered || skippedRegistration)

When we’re dealing with only booleans, there is no nuance. This is a clear and straightforward usage of the JavaScript || operator.

Defaulting a value

You can use the || operator to default the value of a variable, as shown here:

const country = userSuppliedCountry || "United Kingdom"

As we’ve covered, if userSuppliedCountry evaluates to false — for instance if it’s null, undefined, an empty string or some other falsy value, we can set country to the default value of “United Kingdom”.

It’s generally not seen as a good practice to rely too much on this, however.

That’s because there are potential pitfalls whilst doing so. Let’s look at the most common one.

Pitfalls of the JavaScript || operator

Consider the following example:

const shouldDoSomething = (flag) => {
    return flag || true
}

It’s possible to get some (perhaps) unexpected results when utilizing a function such as this one.

For instance, if we invoked the function like so:

shouldDoSomething(false) // true (???)

We’d see true returned. As you can probably tell, that’s definitely not what this function should do!

We want the function to only default to true if no value is specifically passed at all, ideally. So like so:

shouldDoSomething(null) // defaults to true, intentional
shouldDoSomething(undefined) // defaults to true, intentional

So if whatever invokes this function doesn’t pass a boolean for whatever reason, the function assumes a default of true. There’s nothing inherently wrong with this idea in particular.

But as you can see, the function in general is faulty because we cannot pass false and expect an actual false return!

These type of issues are very common pitfalls when dealing with the JavaScript or operator, and as such, this behaviour is definitely something to keep in mind.

In summary

Fundamentally, the JavaScript || operator provides a fairly simple mechanism.

However, as demonstrated, there are some quirks revolving around JavaScript type coercion that should be considered.

If you enjoyed this article or found it useful, feel free to check out my other JavaScript articles.

Thanks for reading!

Have any questions? Ping me over at @justacodingblog
← Back to blog