ES12 Feature you didn't know - Logical Assignment Operators

 


Are you still stuck in ES6? 👀

If so, you probably don't know about ES12, the latest version of ECMAScript which has been released last year. It has been a long time but many people are still not aware of it.

ES12 has introduced some really good additions. In this post, I will present one of its most important updates - Logical Assignment Operators

🤔 What is Logical Assignment Operator?

This is a really cool feature honestly. Let me ask you, what are operators?

👇 This is what google says -

An operator performs some operation on single or multiple operands (data value) and produces a result

 

There are different types of operators. Arithmetic Operators, Logical Operators, Assignment Operators etc.

In ES12, A new kind of operator is introduced. It's the combination of Logical and Assignment Operator.



😕 What are the Operators? 

Let's take a look one by one!

Or Assignment Operator (||=)

As the name says, it assigns the value if the test is falsy! 🔴

For example -

let a = {name: 'Dude'}
a.age ||= 23

//a.age is now 23

a.age was undefined. In Javascript, It's falsy. So, the test passes and assigns the value as 23.


And Assignment Operator (&&=)

It's just the opposite of Or Assignment Operator. It will assign value if the test is true. 🟢

let x = 0
let y = 1

x &&= 0 // 0
x &&= 1 // 0
y &&= 1 // 1
y &&= 0 // 0

If you don't understand the above example, remember, in JS, 0 means false and 1 means true. So, x doesn't pass this test, y does. 


Nullish Assignment Operator

Ahh, a nice one!

It may look similar to Or and it's actually is. This will assign value when the test is nullish (null or undefined). In JS, null is falsy too. But yet, there is another operator. Check this example from mozilla developer docs -

function config(options) {
  options.duration ??= 100
  options.speed ??= 25
  return options
}

config({ duration: 125 }) // { duration: 125, speed: 25 }
config({}) // { duration: 100, speed: 25 }

As you can see, we reduced 6 lines to 2 lines with this simple trick!

🤔 Are these really useful?

Damn, yes! Now, you can remove some if statements. After all, those code blocks sometimes look messy. These simple operators will simplify your code and help to avoid some bugs too hopefully.

Besides, using new features in your old style project will add some spice 😁

Thanks! 👋



Thanks for reading this little post. I hope I was able to introduce you with something that you would love to know.

If you have any question please ask me in the comment below.

Please let me know if you have suggestions as well.

See ya! 😃










Comments