- We all know that == is equality operator is used to compare two values in JavaScript.
- === operator is strict equality operator
- Both == & === are used to compare values in JavaScript. then what is the difference between == and === lets discuss in detail
- == compares two values by converting them to same data types, 10 == ''10" will be true because string type of 10 converted in to number.
- === compares two values without converting them to same data type. 10 === "10"
1. == ( loose Equality)
Checks value equality after type conversion
Converts operands to same type before conversion (ex: 10 == '10' here string 10 will be converted in to number)
2. === Strict equality
- checks value and type without conversion.
- return false if types are different.
Scenario | Loose ==) | Strict (===) |
---|---|---|
5 vs. "5 | true | false |
0 vs. false | true | false |
null vs. undefined | true | false |
NaN vs NaN | false | false |
{} vs {} | false | false |
Explanation:
1. 5 == "5" → true(loose)
- JavaScript converts "5" (string) to 5 (number) before comparison.
5 === "5" → false(strict)
- Different types: number vs. string.
2. 0 == false → true(loose)
false is converted to 0, so 0 == 0 is true.
0 === false → false(strict)
- Number vs. boolean, so different types.
3. null == undefined → true(loose)
- Special case:null andundefined are only loosely equal to each other.
null === undefined → false(strict)
- Different types:null vs.undefined.
4. NaN == NaN → false(loose)
NaN is not equal to itselfin JavaScript.
NaN === NaN → false(strict)
Same reason here: NaN is never equal to anything, including itself.
5. {} == {} → false(loose)
- Objects are compared by **reference**, not by value.
- Different objects in memory, so alwaysfalse.
{} === {} → false (strict)
- Still different object references.
- "5" === "5" returns true
Remember these special cases:
- NaN == NaN will be false even with == operator ,Use Number.isNaN(x) to check for NaN.
- null == undefined will be true
When to use which operator:
- always use === as it is recommended way and which avoids unexpected type conversion
- use == for null/undefined check
- if (x == null) { ... } // Catches both `null` and `undefined`.
No comments