DEV Community

Ambrose Liew
Ambrose Liew

Posted on

The Only Situation To Use ‘==’ In JavaScript

Ever pondered when to use ‘==’ in JavaScript?
Or ever had the idea that one should always use ‘===’ in JavaScript?
Hopefully, by reading till the end of this article, you learned something new!

‘==’ in JavaScript

Why?

You might be thinking, why should one ever consider the scenario to use ‘==’? Just use ‘===’ all the time to ensure consistent and expected developer behavior, this also prevents unexpected bugs from occurring.

And if you’re wondering why it’s bad to use ‘==’, the main reason is that with ‘==’, JavaScript does a Type Coercion.
If you do not know what that is or want to learn more about Type Coercion, you can read about it here.


Well, the main and only reason to utilize ‘==’ in JavaScript is to check for null and undefined at the same time.

if (a == null)
if (a == undefined)
// both methods are equivalent to checking the variable 'a' 
// with null and undefined at the same time.

if (a === null || a === undefined) 
// the equivalence to writing this out
Enter fullscreen mode Exit fullscreen mode

Thus, if you have to do a check for null and undefined at the same time, consider using the ‘==’. This does a shortcut instead of the otherwise, lengthier method of checking for both.


But wait! Ever wondered what is the difference between null and undefined?
And when to use which?

Know that JavaScript will never set any value to null. Both null and undefined represent the absence of value.

Thus, the only difference between the two is that, whenever you want to set a variable to undefined or null, you should always set it to null. Because it helps you during debugging.

If you ever encounter a null value, this means that somewhere along your code, you had manually set the value to null then. Meanwhile, for undefined, you do not know whether you or JavaScript (in other words, not giving it a value when initializing) had set the value to be undefined.


Just as a bonus, here is the pictorial representation of what values are equal to others for ‘==’.

Equality Table for ‘==’

As you can see, there is not much value for using ‘==’, besides checking for null and undefined.


If you felt that you have learned something new, do feel free to follow 🥰, drop a react 💖 or write a comment ✍️!
It helps makes me create and share more valuable content for you to become a better Web Developer! 🤗

Top comments (0)