Many of my friends who are new to JavaScript often ask one common question: "What are the differences between =
, ==
and ===
in JavaScript?"
Operator =
The =
operator is used for variable assignment. It assigns the value on the right-hand side to the variable on the left-hand side:
let a = 1;
const b = 1;
var c = 1;
In JavaScript, =
is also used in assignment expressions, which not only perform assignment but also return the assigned value.
let a = 1;
a = 3; // a: 3
let b = (a = 2); // b: 2, a: 2
This can be useful in certain situations, like assigning a new value within a condition or loop:
let i = 0;
while (++i < 10) console.log(i);
Operator ==
The operator ==
is used for non-strict equally comparison. It compares two values after attempting to convert them to a common type, a process known as type coercion:
function isEqual(a, b) {
return a == b;
}
isEqual(1, 2); // false
isEqual(1, 1); // true
isEqual(1, "1"); // true
isEqual(null, undefined); // true
For instance, 1 == '1'
evaluates to true because JavaScript converts '1'
to the number 1
before comparing.
Because of this type coercion, ==
can yield unexpected result. It's generally recommended to avoid use ==
! One use case I saw before where ==
is acceptable is checking if a value is null
or undefined
, as null == undefined
yield true
:
function isEqualToNullOrUndefiend(value) {
return value == null;
}
isEqualToNullOrUndefiend(null); // true
isEqualToNullOrUndefiend(undefined): // true
isEqualToNullOrUndefiend(false); // false
isEqualToNullOrUndefiend(0); // false
isEqualToNullOrUndefiend(NaN); // false
Operator ===
The operator '===' is the strict equality operator. It checks equality without attempting any type conversion. Both the value and the value type must match for the comparison to return true
:
function isEqualStrict(a, b) {
return a === b;
}
isEqualStrict(1, "1"); // false
isEqual(null, undefined); // false
Summary
| Operator | Description | Example | Result |
| -------- | ------------------------------------- | ----------- | ------- |
| = | Assignment | a = 1 | a is 1 |
| == | Equality with type coercion | 1 == '1' | true |
| === | Strict equality without type coercion | 1 === '1' | false |
In general:
- Use
=
for assignment - Avoid
==
due to type coercion; use===
for comparisons instead.
The ===
operator is uncommon in most of programming languages. However, due to the risks associated with using ==
, JavaScript introduced ===
as a solution!