Monday, July 26, 2010

Difference between ‘==’ and ‘===’ operator in JavaScript

Check Below two javascript functions

function testEqualfn()
{
var a = 10;
var b = "10";
if (a == b)
{
alert("They are equal");
} else {
alert("They are not equal");
}
}

function testTripleEqualfn()
{
var a = 10;
var b = "10";
if (a === b) {
alert("They are equal");
} else {
alert("They are not equal");
}

So, why "10" and 10 are equal when using == operator and not equal when using === operator.

Please find below reasons for operators.

"==" operator compares only the values of the variables. If the types are different a conversion is operated. So the number 10 is converted to the string "10" and the result is compared.

"===" operator compares not only the values but also the types, so no cast is operated. In this case "10" !== 10

No comments: