Values, types and coercion · core
Coercion, == vs === and Object.is
=== compares without converting types; == runs the Abstract Equality algorithm, which converts operands (objects go through ToPrimitive, booleans become numbers); Object.is is like === except NaN equals NaN and +0 differs from -0.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- ToPrimitive turns an object into a primitive: it uses Symbol.toPrimitive if present; otherwise valueOf then toString (hint 'number' or 'default'), or toString then valueOf (hint 'string'). [] becomes '' and {} becomes '[object Object]'.
- Binary +: after ToPrimitive, if either side is a string it concatenates; otherwise it adds numbers. -, *, / and unary + always convert to numbers.
- == rules: null == undefined is true and they equal nothing else; number vs string converts the string to a number; a boolean is converted to a number first; object vs primitive runs ToPrimitive on the object.
- Falsy values: false, 0, -0, 0n, '', null, undefined, NaN. Everything else is truthy, including '0', 'false', [] and {}.
- Relational operators (<, >=) convert null to 0, so null >= 0 is true, but == special-cases null, so null == 0 is false.
- Use === by default. The one common == idiom is x == null, which checks null or undefined.
- Object.is(NaN, NaN) is true and Object.is(0, -0) is false. React compares state and hook dependencies with Object.is.
The red pen
Common traps: mistake → fix
Mistake: == checks value, === checks value and type
Fix: == runs a precise conversion algorithm; know its steps.
Mistake: [] is falsy
Fix: [] and {} are truthy, yet [] == false is true because both sides become the number 0.
Mistake: null >= 0 and null == 0 must agree
Fix: relational operators use ToNumber, equality special-cases null.
Mistake: {} + [] means the same in code and in a console
Fix: at the start of a console line {} is read as an empty block.
Easy to hard
Questions interviewers ask, easy to hard
- What is the difference between == and ===?
- Walk through [] == ![] step by step.
- What does ToPrimitive do? Compare valueOf, toString and Symbol.toPrimitive.
- Why is null >= 0 true while null == 0 is false?
- Where does Object.is matter in React? Implement it.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.