Loose equality and strict equality differ because coercion can silently change operands. The common mistake is letting form strings, nullish values, or NaN produce bugs that explicit conversion and tests should catch.
What is the difference between == and === in JavaScript?
Quick Answer
Answer
The Core Idea
In JavaScript, both == and === compare values, but the real difference is coercion. Loose equality converts operands first, which is why debugging form input, query params, or API payloads gets messy fast.
==converts types before comparing.
===compares value and type exactly as they are.
Operator | Compares | Does Type Conversion? | Example | Result |
|---|---|---|---|---|
| Value only | Yes |
|
|
| Value and Type | No |
|
|
Loose Equality (==)
- Automatically converts operands to the same type before comparing.
- Can cause confusing results because of type coercion.
- Useful only when you explicitly want type conversion.
JAVASCRIPT
console.log('5' == 5); // true (string converted to number)
console.log(0 == false); // true
console.log(null == undefined); // true
console.log('' == 0); // true (empty string converts to 0)
Strict Equality (===)
- Compares both type and value exactly as they are.
- Does not perform type coercion.
- This is the recommended operator for most cases.
JAVASCRIPT
console.log('5' === 5); // false (string vs number)
console.log(0 === false); // false (number vs boolean)
console.log(null === undefined); // false (different types)
console.log(5 === 5); // true
Common Pitfalls
- Using
==can lead to hidden bugs when JavaScript tries to 'help' by converting types.
- Example:
[] == false→true, but[] === false→false.
- Always use
===unless you specifically need type coercion (which is rare).
JAVASCRIPT
console.log([] == false); // true (empty array converts to false)
console.log([] === false); // false
Practical scenario
Compare query parameters or form values (strings) to numbers and booleans in validation logic.
Common pitfalls
==coercion producing surprising results like'' == 0ornull == undefined.- Forgetting
NaNis never equal to itself. - Relying on loose equality in code that should be type-safe.
Use
=== by default; convert types explicitly when needed. Add tests for null, undefined, and NaN.Still so complicated?
Imagine two people named Alex:
- Using == is like saying “they have the same name” — even if one is human and one is a robot.
- Using === is like saying “same name and same species” — no confusion at all.
Summary
- ==: Compares values after converting their types. May return unexpected results.
- ===: Compares both value and type. Safer and preferred in almost all cases.
👉 Rule of thumb: If you’re not sure — use ===.
Similar questions
Guides
Preparing for interviews?
Use the relevant interview-question hub first, then move into a concrete study plan before targeted company sets.