DEV Community

Cover image for When to use ?? and || in JavaScript and TypeScript
Miguel A. Calles
Miguel A. Calles

Posted on • Updated on

When to use ?? and || in JavaScript and TypeScript

In this short post, I want to share a simple way to remember when to use ?? and || when checking values in JavaScript and TypeScript code.

Note: You can read this post on Medium too

When to use ?? when checking a value?

The ?? is an or operator where the left side must be empty before returning the right side.

The question mark ? is like asking yourself, “Does the value exist?”

var ?? varMustBeEmptyToReturnThisVar
Enter fullscreen mode Exit fullscreen mode

Examples

Suppose you get an object where some properties are optional.

const obj0 = { required: 0 };
const { optional } = obj0;
console.log(optional ?? 'no optional property exists');
// returns 'no optional property exists'
Enter fullscreen mode Exit fullscreen mode

Be careful when the property returns a falsy value.

const obj1 = { required: '' };
const { required } = obj1;
console.log(required ?? 'no required property exists');
// returns ''
Enter fullscreen mode Exit fullscreen mode

When to use || when checking a value?

The || is an or operator where the left side must be falsy before returning the right side.

The vertical bar | is like putting up a barrier where only truthy values can stay on the left side.

var || varMustBeFalsyToReturnThisVar
Enter fullscreen mode Exit fullscreen mode

Example

Suppose you get an object where some properties are falsy.

const obj2 = { required: '' };
const { required } = obj2;
console.log(required || 'required property is falsy');
// returns 'required property is falsy'
Enter fullscreen mode Exit fullscreen mode

Conclusion

I sometimes misuse the ?? and || and thought I should write this reminder to myself. Hopefully that helps you too.

Before you go

These are other articles you might enjoy.

Stop Installing Node.js and Global Npm Packages, Use Docker Instead

Five scary Linux commands you should not run

How to Remove Sensitive Data and Plaintext Secrets From GitHub

How to use CryptoJS and Cookies to Work with Secrets in Postman


Photo by Towfiqu barbhuiya on Unsplash

Top comments (0)