The =
operator is an assignment operator - used to assign a value to a variable.
const x = "a"; let y = "b";
The ==
and ===
operators are used to compare two values.
==
can produce unexpected results because it performs type conversion before comparison.
10 == '10'; // true, because '10' (string) is coerced to a number 0 == false; // true, because false (boolean) is coerced to 0 1 == true // true, because true (boolean) is coerced to 1 "" == false // true, because "" (string) is coerced to false NaN == false // false
===
is considered a safer operator because it does not perform conversion before comparison. This means it compares both the value and the type.
10 === '10'; // false 0 === false; // false 1 === true // false "" === false // false NaN === false // false
Comparing Objects
Comparing primitive values is straightforward. However, with objects, it's a bit different in JavaScript due to references, which are virtual strings connecting a variable to its content.
An object created occupies a specific memory space. Multiple references can be assigned to the same object.
const obj = {}; const a = obj; const b = obj; const c = {}; a === b // true a === c // false b === c // false
Comparing references checks whether both point to the same object in memory.
To check if two objects are the same, a deep comparison is necessary. It involves checking if all primitive values that compose the objects match.
When dealing with nested objects, considering writing a function for recursive value comparison or using existing libraries might be beneficial.
const obj1 = {a: {b: "ABC"}, d: 23}; const obj2 = {a: {b: "ABC"}, d: 23}; obj1.a.b === obj2.a.b && obj1.d === obj2.d // true
For an exhaustive article on deep comparison, check here.