Difference between =, == and === in JavaScript
In JavaScript =, ==
and ===
serve different purposes in the context of programming.
= (Assignment Operator) :
Used to assign a value to a variable.
let x = 3; //Assigns the value 3 to the variable x
== (Loose Equality):
Compares two values for equality, allowing type coercion.
Converts operands to the same type before comparison.
0 == '0'; // true (string is converted to a number)
null == undefined; //true
=== (Strict Equality):
Compares two values for equality without type coercion.
Both the type and value must be the same for the comparison to be true.
0 === '0'; // false (different types)
null === undefined; //false (different types)
Use = for assignments.
Use == for loose equality checks.
Use === for strict equality checks.
For reliable comparison, prefer ===.