JavaScript what is the difference between “==” and “===” ?

You may have come across the equality checks many number of times but might have wondered what the difference is?

The double equals “==” checks whether two variables are equal whereas the triple equals “===” not only checks whether the two variables are equal, but also checks whether the two variables are of the same type.

For Example

var variable1=25;

var variable2=25;

if(variable1==variable2){

console.log(“The two values are equal”);

}

else{

console.log(“The two values are not equal”);

}

In this case after the execution of the script, it would print that the two values are equal.

Now take this example,

var variable1=70;

var variable2=”70″

if(variable1==variable2){

console.log(“The two values are equal”);

}

else{

console.log(“The two values are not equal”);

}

In this case, it would still print that the two variables are equal since the two values are equal.

And now let’s take the final example.

var variable1=70;

var variable2=”70″

if(variable1===variable2){

console.log(“The two values are equal”);

}

else{

console.log(“The two values are not equal”);

}

Here we have used the triple equals sign, so do you think the result would be different?

Think about it….

images

It would tell you that the two variables are not equal in spite of having the same value. This is because in addition to checking whether the values are equal, it also checks for the type of the variable. In this case, variable1 is of type Integer whereas variable2 is of type string and hence they are different.

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s