Write the main difference between '==' and '===' operators in javascript?

The main difference between == and === operators in JavaScript is that == performs type coercion (converts types before comparing), while === performs strict comparison without any type conversion.

The == Operator (Loose Equality)

The == operator compares values after converting them to the same type if needed. This can lead to unexpected results.

Example

<html>
<body>
<p id="loose"></p>
<script>
var x = 5;
var y = "5";
var z = 6;
document.getElementById("loose").innerHTML =
(x == y) + "<br>" + (x == z);
</script>
</body>
</html>

Output

true
false

Notice that 5 == "5" returns true because JavaScript converts the string "5" to the number 5 before comparison.

The === Operator (Strict Equality)

The === operator compares both value and type without any conversion. Both operands must be of the same type and have the same value to return true.

Example

<html>
<body>
<p id="strict"></p>
<script>
var x = 5;
var y = "5";
var z = 5;
document.getElementById("strict").innerHTML =
(x === y) + "<br>" + (x === z);
</script>
</body>
</html>

Output

false
true

Here, 5 === "5" returns false because the number 5 and string "5" have different types, while 5 === 5 returns true.

Key Differences

Operator Name Type Conversion Comparison
== Loose Equality Yes Value only (after conversion)
=== Strict Equality No Value and type

Common Examples

<html>
<body>
<p id="examples"></p>
<script>
document.getElementById("examples").innerHTML =
"0 == false: " + (0 == false) + "<br>" +
"0 === false: " + (0 === false) + "<br>" +
"null == undefined: " + (null == undefined) + "<br>" +
"null === undefined: " + (null === undefined);
</script>
</body>
</html>

Output

0 == false: true
0 === false: false
null == undefined: true
null === undefined: false

Best Practice

It's recommended to use === (strict equality) in most cases to avoid unexpected type conversions and make your code more predictable.

Conclusion

Use === for reliable comparisons that check both value and type. Reserve == only when you specifically need type coercion behavior.

Updated on: 2026-03-15T23:18:59+05:30

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements