Explain the difference between == and ===
- 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"
- Use our JavaScript compiler to test your snippets
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)
- 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 |
- "5" === "5" returns true
- NaN == NaN will be false even with == operator ,Use Number.isNaN(x) to check for NaN.
- null == undefined will be true
- 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`.