Logical OR Assignment (||=) in JavaScript: Simplifying Your Code

Let’s dive into the Logical OR Assignment operator - ||=.

This operator will be your new best friend if you love writing concise and clear code.

What is a Logical OR Assignment?

In short, the ||= operator is a shorthand way of saying: "If the variable on the left is falsy, assign the value on the right to it."

Let's Break it Down

Traditionally, you might do something like this:

if (!myVar) {
    myVar = "New Value";
}

With ||=, you can compress that down to:

myVar ||= "New Value";

It’s that simple!

Real-world Example

Imagine you’re setting up user preferences and you want to ensure that if a theme isn’t set, it defaults to "light".

let userTheme;
userTheme ||= "light";
console.log(userTheme); // outputs: "light"

But, if userTheme already had a value, say "dark", it would remain unchanged.

Or another short example:

function setupDevice(config) {
    config ||= { brightness: 50, volume: 70 };
    // ... rest of the setup code 
}

In this, we get a config of { brightness: 50, volume: 70 } if no configuration is passed to setupDevice.

A short recap:

  1. ||= is a shorthand that checks if the left side is falsy.
  2. If it's falsy, it assigns the right side value.
  3. It makes your code cleaner and more readable.

Happy coding! 🚀

JSJavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.