Menu

Difference between == and === in JavaScript

In this post we will see what is the difference between double equals(==) and triple equals(===) compare operator in JavaScript program. 

Double equals (==) 

Double equals compare two values and return true when those values have exactly same text and should be in same case. Please note values are case sensitive in javascript. 
e.g. var a = "Rashid";

       var b = "rashid";
       a==b // It will return false since both the values are not in the same case.

Triple equals (===) 

Triple equals compare two values as well as it also compare the datatype of those value, and return true when both the things (text and datatype) of those values get matched with other value.
e.g. var c = 7;

       var d = "7";
       c===d // it will return false; since c stored a numeric value and d stored a string value hence datatype didn't match for those values.

Compare values ignoring case 

You can also compare the values in javascript by ignoring the case sensitive. To do that first we have to convert given values in either lowerCase or upperCase by using the toUpperCase() or toLowerCase function.
e.g. var a = "Rashid";

       var b = "rashid";
       a.toUpperCase()==b.toUpperCase() // It will return true 

Code snippet

Below is the complete code snippet which you could refer to practice double equals(==) and triple equals(===) in javaScript.

If you face any issue please fill free to ask your question in comment section.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<html>
<head>
    <title>Cpmpare values using == and ===</title>
    <script type="text/javascript">
     var a = "Rashid";
     var b = "rashid";
     var c = 7;
     var d = "7";
     document.writeln("Result of a==b, where a="+a +" b="+b +"::  ");
     document.write(a==b);
     document.write("<br />")
     document.writeln("Result of a===b, where a="+a +" b="+b +"::  ");
     document.writeln(a===b);
     document.write("<br />")
     document.writeln("Result of a===b with toUpperCase, where a="+a +" b="+b +"::  ");
     document.writeln(a.toUpperCase() === b.toUpperCase());
     document.write("<br />")
     document.writeln("Result of c==d, where a="+c +" b="+c +"::  ");
     document.writeln(c==d);
     document.write("<br />")
     document.writeln("Result of c===d, where a="+c +" b="+c +"::  ");
     document.writeln(c===d);
     document.write("<br />")
    </script>
</head>
<body>
<span>This code snippet is copyright with rashidjorvee.blogspot.com.</span>    
</body>
</html>

Output

Result of a==b, where a=Rashid b=rashid:: false
Result of a===b, where a=Rashid b=rashid:: false
Result of a===b with toUpperCase, where a=Rashid b=rashid:: true
Result of c==d, where a=7 b=7:: true
Result of c===d, where a=7 b=7:: false 

No comments:

Post a Comment