In JavaScript, == is the loose equality operator that compares values after type conversion, while === is the strict equality operator that compares both value and type without conversion. Edge cases include null/undefined and NaN, so prefer explicit conversion and add tests.
What is the difference between == and === in JavaScript?
Preparing for interviews?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
Quick Answer
Answer
The Core Idea
In JavaScript, both == and === are used for comparing two values, but they behave very differently.
==(loose equality) converts the operands to the same type before comparison.===(strict equality) checks both value and type without converting anything.
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