KatInterview

JavaScript Strict vs Loose Equality: Coercion Rules and Pitfalls

StringsModel answer
MediumModel answerStringsjavascripttype-coercionequality

Last updated

Explain how JavaScript's two equality operators work, how implicit type coercion drives loose equality, where results diverge, and which operator to prefer.

JavaScript has two ways to test whether values are equal: the double-equals form (==) and the triple-equals form (===).

Write an answer that covers the following:

  1. Describe the steps each operator takes when it compares two values.
  2. Define implicit type coercion and explain how it connects to ==.
  3. Give concrete expressions where the two operators return different results, and explain each result. Include at least one case where both operators return false even though the result may look surprising.
  4. State which operator you would use by default on a team, justify the choice, and mention any situation where you would deliberately choose the other one.

Bonus points for discussing how objects are compared, what happens with NaN and signed zero, and whether == is transitive.

Hints

Hint 1

Start with the simplest rule: `===` never converts anything. If the two operands have different types it answers `false` right away. Then ask what `==` does differently when the types differ.

Hint 2

For `==`, remember the order of conversions: `null` and `undefined` are special, strings convert to numbers, booleans convert to numbers (not the other way round), and objects convert to primitives before the comparison is retried.

Hint 3

Test your understanding on `[] == false`, `"2" == true`, `null == 0` and `"" == "0"`. Work out each result by applying one conversion at a time, and notice what this reveals about transitivity.