==
and ===
in JavaScriptIn JavaScript, ==
and ===
are comparison operators, but they work differently:
==
(Equality Operator) compares two values for equality after converting both values to a common type. This is known as type coercion.===
(Strict Equality Operator) compares two values for equality without performing any type conversion. This means both the value and the type must be the same for the comparison to return true
.Consider the following examples:
console.log("2" == 2); // Output: true
console.log("2" === 2); // Output: false
"2" == 2
, JavaScript converts the string "2"
to a number 2
before comparing, so the result is true
."2" === 2
, JavaScript compares the string "2"
with the number 2
without type conversion. Since the types are different (string vs. number), the result is false
.