QA Interview Hub · Knowledge base · Quizzes · Українська

TypeScript › JS traps: numbers and money, strings, dates, objects and arrays

Comparison: == and ===, ||, ?? and ?.

The == operator compares with type coercion and === without it, so === is the default choice. For defaults nullish coalescing beats || because it reacts only to null and undefined, while || replaces any falsy value (0, an empty string, NaN), so a zero fee turns into the default. Excessive optional chaining in tests hides a missing field, so check the response structure first.

TypeScript · JS traps

A fee of 0 became 500 because the code had ||. Why did the zero «vanish» and how does ?? help?

The business case «zero fee for premium clients» works only on the backend. In the interface after a migration to the new API the client sees a fee of 500. The cause is one line: const fee = response.fee || 500. Zero in JS is «falsy» so || decides there is no value and substitutes the default. That is not a rare case but a consequence of how JS coerces types. In this lesson we go through comparison and substitution operators, where they differ from expectations and how a test misses a bug because of them.

How it works and why. == coerces types by complicated rules, === does not: different types give false. Some results of == are not obvious:

'' == 0;             // true
'0' == false;        // true
null == undefined;   // true
null == 0;           // false
null >= 0;           // true   (relational operators coerce null to 0)
NaN == NaN;          // false
[1] == 1;            // true

Hence the practical rule: always === and !==. The ESLint rule eqeqeq enforces it, and the exception x == null (a check for null and undefined together) is considered acceptable, although an explicit x === null || x === undefined reads less ambiguously. Separately: null == 0 is false while null >= 0 is true because relational operators coerce null to 0. TypeScript helps only partly, as an error on comparing different types:

const s: string = 'a';
if (s === 1) {}
// TS2367: This comparison appears to be unintentional because the types
// 'string' and 'number' have no overlap.

The error appears only for types that do not overlap. Everything that overlaps (number | string with number) TypeScript lets through, so it does not catch implicit coercion by ==.

Example: || versus ??. || returns the right operand if the left one is falsy. There are eight falsy values: false, 0, -0, 0n, '', null, undefined and NaN. The ?? operator (nullish coalescing) substitutes the default only for null and undefined:

const a = response.fee || 500;     // fee = 0 becomes 500: a bug
const b = response.fee ?? 500;     // 0 stays 0
const c = Number(process.env.TIMEOUT) || 30_000;
// here || is fitting: it catches both NaN and 0

settings.retries ??= 3;            // assign only if null or undefined

A default for an API response with a zero

Wrong

response.fee || 500

A zero fee, an empty string and NaN are replaced with the default. A valid business case becomes a bug without any message.

Right

response.fee ?? 500

The default only when the value is really absent. Zero stays zero: for money, limits and counters this is what is needed.

Figure 1. The choice between || and ?? depends on whether 0 or an empty string is a valid value.

This does not mean || is always bad. For a timeout from an environment variable (Number(env.TIMEOUT) || 30_000) it is fitting because it catches both NaN and 0, which are equally invalid here. JS forbids mixing ?? with || or && without parentheses:

const x = a ?? b || c;       // SyntaxError
const y = (a ?? b) || c;     // parentheses are required

Optional chaining and tests. ?. stops evaluation and returns undefined if the left part is null or undefined: res.data?.items?.[0]?.amount. In application code it is convenient, and in tests an excessive ?. masks a problem: it turns «the field is missing» into undefined, and a missing field and an empty array give the same check result:

type Body = { data: { items: { amount: number }[] } };
declare const body: Body;

// weak: passes for [] and when the items field is missing altogether
expect(body.data?.items?.length).toBeFalsy();

// exact: fails if items is missing and points at the real difference
expect(body.data.items).toEqual([]);

First the structure is checked explicitly (the field exists and has the expected type) and then the value. Then the failure points at the real cause. If TypeScript knows the field is required, ?. is simply superfluous there (and the @typescript-eslint/no-unnecessary-condition rule will say so).

Limits and alternatives. The toBe matcher compares through Object.is and not ===, and this shows on edge values:

expect(NaN).toBe(NaN);       // passes: toBe uses Object.is
expect(0).toBe(-0);          // fails: Object.is(0, -0) is false
expect(0).toEqual(-0);       // also fails: toEqual tells +0 and -0 apart

For checking NaN in a test toBe(NaN) or Number.isNaN is enough, and x === NaN is always false. For objects and arrays === compares references, so for content toEqual or toStrictEqual is needed. The difference between toEqual and toStrictEqual also concerns undefined: the first ignores fields with the value undefined, the second does not.

Common mistakes.

  • || for defaults where 0 or an empty string is valid: a zero fee, a limit, a counter.
  • == instead of === without a clear reason: '0' == false and [] == false are true.
  • a ?? b || c without parentheses: SyntaxError.
  • A ?. chain in a test check: a missing field and an empty value give the same green result.
  • x === NaN and if (x) as a «number exists» check: zero is falsy too.

Check yourself

What will const limit = config.limit || 100 return for config.limit = 0, and which value does the business expect if 0 means «no limit»?

Answer

100: zero is falsy so || substitutes the default and «no limit» turns into a limit of 100. ?? is needed so the default is substituted only for null and undefined. It is also worth checking whether 0 really means «no limit» in the contract.

A test expect(res.body?.errors?.length).toBeFalsy() is green. Does that guarantee there are no errors?

Answer

No. It passes for errors: [] and also when body or errors are missing altogether, including when the response has a different shape (for example an error page in HTML). It is more reliable to check the structure first (expect(res.body.errors).toEqual([]) or the status) and then the value.

In an interview. Junior: I always use === because == does a non-obvious type coercion. For defaults I take ?? and not || because || will replace a valid zero, for example a zero fee. Middle/Senior: I know the eight falsy values and that ?? reacts only to null and undefined; I leave || where 0 and NaN are really invalid (a timeout from a variable). In tests I do not hide a missing field behind ?.: I check the structure first, and I remember that toBe works through Object.is.

More articles in this chapter