Tech Interview RoomStudy guides

JavaScript

What is the difference between == and ===? What are truthy and falsy values?

Beginner · 2 min read · Lesson 3 of 12 in JavaScript

  • === (strict equality) compares type and value with no conversion.
  • == (loose equality) converts the operands to a common type first, which gives surprising results.
  • Object.is is like === but treats NaN as equal to NaN and +0 as different from -0. React uses it to compare state.

Surprising == results

  • 0 == '' is true, '0' == false is true, but '' == '0' is false.
  • null == undefined is true, but neither equals 0 or false.
  • [] == false is true, because [] becomes '' and then 0.

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.