comparison
===
==
operator
javascript
Which equals operator (== vs ===) should be used in JavaScript comparisons?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
In JavaScript, the == and === operators are both used for comparisons, but they behave differently:
1. === (Strict Equality)
- Type Comparison:
===checks for both value and type equality. This means that the two values must be of the same type and have the same value to be considered equal. - No Type Coercion: The
===operator does not perform type coercion. If the types of the two values being compared are different, the comparison will returnfalse.
Example:
2. == (Loose Equality)
- Type Coercion:
==checks for value equality, but it performs type coercion if the types of the two values are different. This means that it will try to convert one or both values to a common type before making the comparison. - Less Predictable: Because of type coercion,
==can lead to unexpected results, making it less predictable.
Example:
Best Practice: Use ===
- Predictability: Using
===(strict equality) is generally considered best practice in JavaScript because it avoids unexpected results due to type coercion. It ensures that your comparisons are both type-safe and value-safe. - Clarity: It makes your code more explicit and easier to understand, as you are always certain that the comparison is checking both type and value.
When to Use ==
- Legacy Code: In some cases,
==might be used in legacy code or specific situations where type coercion is desired. However, this should be done with caution and understanding of the behavior.
Summary
- Use
===: Preferred for most cases due to its strict equality check, avoiding type coercion. - Use
==: Only if you are intentionally taking advantage of type coercion and fully understand the implications.
By default, you should use === to make your code more robust and avoid the pitfalls of type coercion that can occur with ==.
Related reading
- Why does my JavaScript code receive a "No ''Access-Control-Allow-Origin'' header is present on the requested resource" error, while Postman does not?
- A good solution for await in try/catch/finally?
- Ability to abort asynchronous call
- About *.d.ts in TypeScript
- Access a variable outside of .then function
- Accessing an object property with a dynamically-computed name
- add fixed parameter to await callback
- addEventListener vs onclick
.png&w=3840&q=75)
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.