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:
||=
is a shorthand that checks if the left side is falsy.- If it's falsy, it assigns the right side value.
- It makes your code cleaner and more readable.
Happy coding! 🚀