What is the difference between == and === in JavaScript?
JavaScript
== vs ===
Both == and === check the types of their operands. The difference is in how they respond if the types don't match. The == allows coercion when types don't match and === disallows coercion.
// == Examples (loose equality)5 == "5" // true (string "5" is converted to number 5)0 == false // true (false is converted to number 0)null == undefined // true[] == false // true (both are converted to 0)// === Examples (strict equality)5 === "5" // false (different types)0 === false // false (different types)null === undefined // false[] === false // falseAs a best practice, it's generally recommended to use === because:
- It's more predictable since no type conversion occurs
- It helps prevent subtle bugs caused by unexpected type coercion
- It makes your code's intentions clearer
Always use triple equals, ===, unless you have a specific reason to use ==.
The only time you might want to use == is when you specifically want type coercion, but those cases are rare and should be clearly documented.