ā¤ Like
šŸ”– Save
šŸ”— Share
@thedevspaceio
@thedevspaceio

== vs === in JavaScript

@thedevspaceio

āš–ļø Compare == and === in JavaScript

JavaScript has two equality operators, loose equality (==) and strict equality (===). This guide explains the differences between them and how to use them correctly.

āœ… Loose equality (==) āœ… Strict equality (===) āœ… Common coercion surprises āœ… Object identity āœ… Comparing NaN āœ… Best practices

#javascript #equality #strictequality #looseequality #typecoercion #comparison #webdev


Comparing == and ===

OperatorNameCompares typesConverts typesWhen to use
==Loose equalityNoYesRarely, when intentional coercion is desired
===Strict equalityYesNoPreferred default

Loose equality (==)

== converts operands to a common type before comparing.

This can produce surprising results.

js
0 == "0"; // true (string converted to number)
"" == 0; // true (empty string converted to 0)
null == undefined; // true
"1" == true; // true (both convert to 1)

Strict equality (===)

=== compares both value and type.

No type conversion happens, so the results are predictable.

js
0 === "0"; // false (different types)
"" === 0; // false
null === undefined; // false
"1" === true; // false

=== is recommended for equality checks because == sees all of these as equal:

js
[] == ""; // true
[] == 0; // true
"" == 0; // true
false == "0"; // true

Object identity

Objects, arrays, and functions are compared by reference, not by contents.

Two objects with the same contents are not strictly equal.

js
const a = {};
const b = {};
a === b; // false (different references)
 
const c = a;
a === c; // true (same reference)
 
[1, 2, 3] === [1, 2, 3]; // false

Comparing NaN

NaN is the only value that is not equal to itself, even with strict equality.

js
NaN === NaN; // false
NaN == NaN; // false

Instead, use Number.isNaN() to check for NaN:

javascript
Number.isNaN(NaN); // true
Number.isNaN("not a number"); // false

Full-Stack AI Developer Roadmap

From HTML & CSS to working with AI models, all in one structured roadmap.

@thedevspaceio
www.thedevspace.io