Difference between ‘==’ operator and ‘===’ operator in JavaScript
First try the following sample code, and have a quick look at the code.
<html>
<head>
<title>Test == and === operators in JavaScript </title>
<script type="text/javascript">
function testEqual(){
var a = 30;
var b = "30";
if (a == b) {
alert("They are equal");
} else {
alert("They are not equal");
}
}
function testTripleEqual(){
var a = 30;
var b = "30";
if (a === b) {
alert("They are equal");
} else {
alert("They are not equal");
}
}
</script>
</head>
<body>
<p>Test == operator: <a href="#" onclick="testEqual();">Click</a></p>
<p>Test === operator: <a href="#" onclick="testTripleEqual();">Click</a></p>
</body>
</html>
So, why "30" and 30 are equal when using == operator and not equal when using === operator.
This happens because of the following behavior of the two operators.
"==" operator compares only the values of the variables. If the types are different a conversion is operated. So the number 30 is converted to the string "30" and the result is compared.
"===" operator compares not only the values but also the types, so no cast is operated. In this case "30" !== 30
Sphere: Related ContentRelated posts brought to you by Yet Another Related Posts Plugin.



Thank you very much for your explanation.
Thanks for the explanation