Thursday, February 11, 2016

Difference between == and === with Example-JavaScript

This is one of the most frequently asked question in interview when one tries to judge your jQuery orJavaScript concepts.

JavaScript provides different types of operators. Here, we will be talking about strict equality andType converting equality.
Strict equality (===) means values which we are comparing must have the same type. 
This means "2" will not be equal to 2 ("2"===2 it will return false)
Type converting equality (==) means automatically it will covert variable to value irrespective of data type, either it is string or number. This means "2" will be equal to 2 ("2" == 2 it will return true)
So the double equal (==) is an auto type converting equality and three equal (===) is strict equality operator i.e it will not covert values automatically.
Difference between == and === with Example-JavaScript
Below is the demonstration with simple examples:

Demo 1

1==”1″ // it will return true because here string will converted as number
1 === “1” // it will return false because here 1 is number and “1” is string

Demo 2

0 == false // it will return true because here false is equivalent of 0
0 === false // it will return false because both are different operands
I have included the complete example for you to check the result yourself as shown below:
<!DOCTYPE HTML>
<html>
<head>
<title>Jquery - Difference between == and ===</title>
<script type="text/javascript">
function CheckDifference() {
 var val = "2";
 document.write("Value for a variable is : " +val +"<br/>"); 

 if (val == 2)
 document.write("== returns True <br/>")
 else
 document.write("== returns False <br/>")

 if (val === 2)
 document.write("=== returns True <br/>")
 else
 document.write("=== returns False <br/>")
}
</script>
</head>
<body>
<h2>JQuery or JavaScript - Difference between == and ===</h2>
<hr/>
<br/>
<div id="div1">
<input type="button" id="Check" 
 onclick="CheckDifference()" 
 value="Click to Check Difference" />
</div>
</body>
</html>