Understand “==” and “===” operator in JavaScript
Understand “==” and “===” operator in JavaScript
In this small article we will understand the difference between
“==” and “===” operator in JavaScript. It’s very important to understand the difference
between them otherwise programmer might do big mistake in code development and
as side effect program might work unexpectedly.
Let’s try to understand the basic difference between them.
“==” operator checks the value not type where “===” operator
check value and type both. Let’s try to implement with suitable example.
Understand “==” operator
In this section we will understand “==” operator with example.
In first example we will compare Boolean value with string. Have a look on
below code.
<body>
<form id="form1" runat="server">
<script>
var value = false;
if (value == 0)
alert("Both are same, but type is not")
else
alert("Not Same");
</script>
</form>
</body>
In this example within if condition we are checking “false”
with “0”. And the output screen is saying that.
Both are same in terms of value. Try with string and “false”,
let’s see the result.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<script>
var value = false;
if (value == "0")
alert("false and 0 are same")
else
alert("Not Same");
</script>
</form>
</body>
</html>
Here is sample output. Again we are seeing that both are
same.
So, we are seeing that “==” operator is checking only value
not type. Now we will see how “===” operator works.
Understand “===” operator
As we told earlier that “===” checks the value and it’s
type. Let’s try to compare “false” and “0” using “===” operator. Here is sample
code.
<body>
<form id="form1" runat="server">
<script>
var value = false;
if (value === "0")
alert("false and 0 are same")
else
alert("false and 0 ,type mismatch");
</script>
</form>
</body>
Here is sample output. We are seeing that the type does not
match.
Let’s try with both Boolean variables. Have a look on below
code.
<body>
<form id="form1" runat="server">
<script>
var value = false;
if (value === false)
alert("false and false matches")
else
alert("type mismatch");
</script>
</form>
</body>
This is the output.
We are seeing that both are same in terms of value and type
because if condition has satisfied.
Conclusion:-
In this small article we have seen how “==” and “===”
operator works in JavaScript.