Difference between "==" and "===" in JS

Most of us coming from different language background (Java, C , C++) have a confusion around "==" and "===" in JavaScript.

As you know Javascript is loosely type language . What I mean to say here is that , you can declare an variable and you have option to assign value type i.e int , float and string. Javascript interpreter will not complain you in that regard .

var a, b , c;
a = 1;
b = 3.14;
c = "Hello world!";

Even when you try to operation between two different typeof value , JS interpreter will convert the variable values for you, if possible. In the below example , the variable b get converted into String and then concatenation operation is performed .

console.log(c + " " + b);
//Hello world! 3.14

Basically , "==" is kind of legacy bug , that compare the value and also try to do the type conversion, if required. Here , in the below code , though the string value is being compared to int value , which is not same (as in Java , C , C++). But JS interpreter, do that job for you and convert the string value to int and then do comparison , which make it true.

if ( 10 == "10") {
   console.log("Both values are same.")
}
//Both values are same.

If you are using "===" , you are asking the interpreter , to stop any of the above conversions. As JS already had "==" operator , JS designer decided to include an additional operator 3 equal to operator "===" for this kind of comparison operation.

if (5 === "5") {
  console.log("Both values are same.")
} 
else {
     console.log("values are not same.")
}
//values are not same.

In my experience, I will suggest always to use "===" in your Node or any other JS scripts, to save your unnecessary bug.

To view or add a comment, sign in

More articles by abuzar hamza

  • Scope in JS

    Scope in JavaScript create a lot of confusion in programmer having C language family experience. All language has…

  • Difference between undefined and null in JS

    I have been working in the industry from the long time and have noticed that due to the different language background ,…

Others also viewed

Explore content categories