Truthy/falsy, pass-by-value vs reference, and strict equality: practical use case

HighIntermediateJavascript
Quick Answer

This is a high-frequency bug pattern: defaults that overwrite valid falsy values, loose equality coercion surprises, and accidental shared-object mutation. Robust code uses ??, ===, and controlled immutability.

Answer

Why interviewers combine these topics

Because real frontend bugs usually combine them: a fallback breaks 0/false, a loose comparison silently passes, and a helper mutates shared state.

Topic

Bad habit

Safer habit

Truthy/falsy defaults

value || fallback

value ?? fallback

Equality checks

== on unknown input

Parse first, compare with ===

Object handling

Mutate input object

Clone/return new object unless mutation is intentional

Three rails that prevent many production bugs.
JAVASCRIPT
const retries = 0;
const enabled = false;

console.log(retries || 3);   // 3   ❌ loses valid 0
console.log(enabled || true); // true ❌ loses valid false

console.log(retries ?? 3);    // 0   ✅
console.log(enabled ?? true); // false ✅
                  
JAVASCRIPT
console.log('0' == 0);  // true  (coercion)
console.log('0' === 0); // false

const qty = Number('0');
console.log(qty === 0);  // true ✅ explicit conversion first
                  
JAVASCRIPT
function normalize(input) {
  const cfg = { ...input }; // avoid mutating caller
  cfg.retry = cfg.retry ?? 3;
  if (cfg.total === 0) cfg.status = 'empty';
  return cfg;
}

const original = { retry: 0, total: 0 };
const out = normalize(original);

console.log(original); // unchanged
console.log(out);      // normalized safely
                  

Integrated real-world bug (before/after)

JAVASCRIPT
// ❌ buggy
function prepare(cart) {
  cart.retry = cart.retry || 3;
  if (cart.total == '0') cart.status = 'empty';
  return cart;
}

// ✅ safer
function prepareSafe(input) {
  const cart = { ...input };
  cart.retry = cart.retry ?? 3;
  if (cart.total === 0) cart.status = 'empty';
  return cart;
}
                  

Test checklist
Always include cases for 0, false, empty string, string-number input, and "original object unchanged" assertions.

Still so complicated?

Think of this as three guardrails: default correctly, compare strictly, and protect shared state.

Summary
      • Use ?? when 0/false/'' are valid.
      • Use === after explicit parsing.
      • Avoid mutating caller-owned objects by default.
Similar questions
Guides
Preparing for interviews?

Use the relevant interview-question hub first, then move into a concrete study plan before targeted company sets.