wasAsked.

What is the difference between == and === in JavaScript?

Frequently Asked (All Companies) · Role not specified · technical

Published

Year not specified · JavaScript

Community answers

Posted by wasAsked editorial collection

== (loose equality) compares values after type coercion. === (strict equality) compares both value and type, without any conversion. Strict equality (===) - True only if both operands have the same type and the same value. 5 === 5 // true 5 === '5' // false — number vs string true === 1 // false null === undefined // false - Objects (including arrays and functions) are equal only if they are the same reference: {} === {} // false const a = [1]; const b = a; a === b // true Loose equality (==) - If the types differ, JavaScript converts one or both operands following the Abstract Equality Comparison rules, then compares. 5 == '5' // true — string converted to number true == 1 // true — boolean converted to number false == 0 // true '' == 0 // true null == undefined // true — special rule null == 0 // false — null only loosely equals undefined [1] == 1 // true — array converted to primitive "1", then to number '0' == false // true These rules produce surprising results that cause bugs: '' == '0' // false 0 == '' // true 0 == '0' // true — equality is not transitive Special cases for both operators NaN == NaN // false NaN === NaN // false — NaN is not equal to anything, including itself Use Number.isNaN(value) to check for NaN. +0 === -0 // true Object.is(NaN, NaN) // true Object.is(+0, -0) // false — Object.is is "same value" equality Best practice - Use === and !== by default; they are predictable and clearer about intent. ESLint's eqeqeq rule enforces this. - A common, deliberate exception: value == null checks for both null and undefined in one comparison (equivalent to value === null || value === undefined). Some teams allow this pattern explicitly; others prefer the explicit form or the nullish coalescing operator (??). TypeScript TypeScript reports errors for comparisons between types with no overlap (for example comparing a number to a string with ===), catching many mistakes at compile time, but runtime semantics are the same as JavaScript. Performance === is never slower than == and avoids coercion work, though the difference is negligible; correctness is the real reason to prefer it. Interview summary: "== compares after type coercion, which leads to surprising results like 0 == '' being true. === compares type and value without coercion. Always use === except for the deliberate value == null idiom, and remember that NaN never equals itself and objects compare by reference."

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics