loading...
Cover image for  == (or) ===? What do you prefer and why?

== (or) ===? What do you prefer and why?

dineshmadanlal profile image dineshmadanlal ・1 min read

I prefer === because I personally feel that we as devs should have control over our code. Though javaScript is a tricky language, we should have control of what's being stored in a variable. For example,

isAlive is a boolean which should have false, true and not null.

I know it's a hard thing to follow but trust it does wonder when we have control over what's being stored. Especially on Frontend codebase.

Your thoughts? Keen to learn something new :)

Discussion

markdown guide
 

== and === are different operators. It's not about preferences but how you want to enforce equality.

When using ==, JavaScript will do type coercion to see if both values are equal to each other. This will have unfortunate side effects, depending on how you use it.

For example, take the value 1 and the string "1". Are these to values equal? No, not really. One is a string, and one is a number.

Let's see what using == has to say. If you go into your console or launch node and type in 1 == "1" you should see the following.

> 1 == "1"
true

Dang, that isn't right!

Now, let's take a look at ===. The === operator does exact equality checking, no type coercion. If you go back to run the code 1 === "1" well see the following

> 1 === "1"
false

That more like it! You should always default to using === to ensure equality checks are making exact comparisons. Sometimes you might need to use == but those situations are going to be pretty limited.

An example of a special case like that is a comparison of a string literal and a String object.

> "abc" == new String("abc")  
true

> "abc" === new String("abc")  
false
 
 

If your in a strictly typed environment, using triple equals is essential.

Double equals is more situational. It has it's uses. I've never seen the side-effects people worry about, but maybe my style of coding is clean enough that I actually don't need to worry about type errors.

My big worry with triple equals is in the world of web, you sometimes get unexpected values i'd rather Javascript try to make it work.

I often use an early/escape, early return pattern for validation. I much prefer a loser interpretation here, because loose equality when your taking about validation is actually more 'strict' in terms of defending your application.

ie

if( someNumber == 0 )
   return false

If your getting data from a web request, and something wacky happens in the parsing, I still want the validation method to return false, even if it got a string zero instead of a number zero.

 

I don't even remember the last time I used ==. IMHO it can be error prone and sometimes it can have unexpected results, or just be downright weird.