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

2Milinda3rd Nov 2008JavaScript

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 Content

Related posts brought to you by Yet Another Related Posts Plugin.

2 Comments Comments Feed

  1. Jkrishna (November 21, 2008, 8:25 am).

    Thank you very much for your explanation.

  2. Amika (February 13, 2010, 9:48 pm).

    Thanks for the explanation

Add a Comment