People who are new to programming often find it difficult to understand the difference between
In mathematics we only use
=, so what do the other two mean?
= is an assignment operator, while
=== are called equality operators.
In mathematics and algebra,
= is an equal to operator. In programming
= is an assignment operator, which means that it assigns a value to a variable.
For example, the following code will store a value of
5 in the variable
let x; // declaring a variable. x = 5; // assigning a value of 5 to the variable.
We can combine the declaration and assignment in one line:
let y = 10;
It may look like the assignment operator works the same way as algebra’s equal to operator, but that’s not the case.
For example, the following doesn’t make any sense in algebra:
x = x + 4;
x + 4 and store this value in
The equality operator returns
false based on whether the operands (the values being compared) are equal.
For example, the following code will return
let x = 5; // declares x and assigns x to the value 5 x == 8; // returns false
Interestingly, if we compare an integer
5 and a string
"5" it returns
5 == "5"; // returns true
Like the equality operator above, the strict equality operator compares the two values. But unlike the equality operator, the strict equality operator compares both the content and the type of the operands.
So using the strict equality operator,
"5" are not equal.
5 === "5"; // returns false
It is better to use the strict equality operator to prevent type conversions, which may result in unexpected bugs. But if you’re certain the types on both sides will be the same, there is no problem with using the shorter operator.