Hoppa till huvudinnehåll

|| vs ??

· 2 min att läsa
Filip Tammergård
Software Engineer at Einride

|| and ?? are similar, but there's some very important nuance. Take a look at this example:

const a = "" || "default value"
// > "default value"

const b = "" ?? "default value"
// > ""

Let me explain.

Logical OR operator

Let's pretend you are the logical OR operator (||). You see one value to the left and one value to the right. You start looking at that value to the left. If that value is truthy, that's the value you pick. If the left value is falsy, you pick the other value.

To understand your task, you have to know what truthy and falsy values are.

Truthy and Falsy values

Here are all falsy values in JavaScript:

  • number 0
  • bigint 0n
  • keyword null
  • keyword undefined
  • boolean false
  • number NaN
  • empty string "", '', or ``

All other values are truthy.

Nullish coalescing operator

Now let's pretend you are the nullish coalescing operator (??). Again, you see one value to the left and one value, and you start looking at the value to the left. This time, if the left value is nullish, you pick the other value. If the left value is not nullish, that's the value you pick.

This assignment requires knowledge about nullish values.

Nullish values

Here are all nullish values in JavaScript:

  • keyword null
  • keyword undefined
anteckning

As you can see, all nullish values are falsy, but not all falsy values are nullish.

Try it out!

A good way to solidify knowledge about this difference is to experiment with it. In the code below, there is a leftValue and a rightValue variable. You can select what value you want leftValue to take. Then you'll see what the two operators will output.

const leftValue = 0
const rightValue = "This is a default value that could be anything."

leftValue || rightValue
// > This is a default value that could be anything.

leftValue ?? rightValue
// > 0

Now you know when to use || and when to use ??! 🎉

Conclusion

  • Be intentional when you choose between || and ??—using the wrong operator can cause bugs.
  • Use ?? when you only want to specify a fallback for nullish values (null and undefined).
  • Use || when you want to specify a fallback for all falsy values.

References