This is one of the common question in JavaScript interview.  Since JavaScript supports both strict equality comparison and type converting equality. So let’s understand which operator is used for which operation.

As i said that, === this operator considers the data type of the variable and == this operator considers the value of the variable,

Following are couple of more differences between == and === in JavaScript:

 

    •   When we compare two different data type of variables. for example if  we compare string with number or Boolean with string using == operator, then it automatically converts the one type of variable to other so it can be compare and return true based upon the value. if we use === operator which is strictly equality then it will only return true when both data type and value of variables are same. this will be much clear with the following examples of == and === JavaScript.

     

    • == operator is know as type coercion operator and anytime if both values are same but not data type using this == type coercion will happen. On other hand if we use === operator this will check both data type and value. you should use === operator over == operator for comparison.
    • Also if there is any difference between == and === then there is also difference between != and !==.
      It is easy to guess that != operator only checks the value and !== operator will consider both data type and value of the variables.
    • What will happen if we compare NaN (not a number) with any number or with it self? its a special case that in JavaScript NaN is not equal to anything even itself.



You should use Strictly equality operator for comparison avoid using == operator this. Even if you need type coercion, Instead convert the type by yourself.

By the way it was one of the interesting JavaScript interview question you can expect this type of question in beginner level JavaScript Interview.

For JavaScript documentation you can visit Mozilla Developer’s site here.


Suraj Sharma

Developer who never forgets semicolon.

4 Comments

klout · March 18, 2018 at 7:48 am

I like the valuable information you provide in your articles.
I’ll bookmark your blog and check again here regularly.
I am quite certain I’ll learn many new stuff right here!
Good luck for the next!

Yugansh Tyagi · March 18, 2018 at 10:52 am

Nice article, many people don’t explain these things in detail.
Keep going

    Sharma · March 18, 2018 at 11:38 am

    Glad you liked it. thanks alot for your precious support.

Purushottam · September 21, 2018 at 10:30 pm

Very good bhai! Keep it up!

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: