What is the difference between == and ===? What are truthy and falsy values?
===(strict equality) compares type and value with no conversion.==(loose equality) converts the operands to a common type first, which gives surprising results.Object.isis like===but treatsNaNas equal toNaNand+0as different from-0. React uses it to compare state.
Surprising == results
0 == ''is true,'0' == falseis true, but'' == '0'is false.null == undefinedis true, but neither equals0orfalse.[] == falseis true, because[]becomes''and then0.
Rule: always use ===. The one accepted exception is x == null, which checks for both null and undefined.
Falsy values
There are exactly eight: false, 0, -0, 0n, '', null, undefined, NaN. Everything else is truthy, including '0', 'false', [] and {}.
Example
js
console.log(NaN === NaN, Object.is(NaN, NaN)); // false true
console.log([] ? 'truthy' : 'falsy'); // truthy
const count = 0;
console.log(count || 10); // 10: 0 is falsy, so the default wins
console.log(count ?? 10); // 0: ?? only replaces null and undefined
const user = null;
console.log(user?.address?.city ?? 'unknown'); // unknown?? (nullish coalescing) and ?. (optional chaining) avoid the classic bug where a valid 0 or '' is replaced by a default.
Follow-up questions interviewers ask
Try answering each one before you open it.
Why does a React component render 0 on screen with {count && <List/>}?
&& returns the left operand when it is falsy, so with count === 0 the expression is 0, and React renders numbers. Write {count > 0 && <List/>} or use a ternary.