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

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

Strings, dates, mutations and sorting

Typical JS traps: sort() without a comparator sorts as strings and mutates the array, months in Date start from zero, and spread makes only a shallow copy. Ukrainian strings are compared with localeCompare or Intl.Collator, dates are exchanged in ISO 8601 with a zone, and TZ is fixed on CI. Use structuredClone for a deep copy, but it has limits, such as functions.

TypeScript · JS traps

A test fails only on CI and only in the hours before midnight UTC. Dates, sorting or copying?

Four different bugs in three tests: a list sorting check on the UI passes locally and fails on CI; the date «created on 15 January» turns into «14 January» in a report; a sorted array in a fixture changes the order in another test; a «copy» of test data corrupts the original. They have nothing in common except the source: the behaviour of JS in «everyday» operations on strings, arrays and dates that differs from what a person expects. The lesson collects the most frequent cases and gives rules for protecting against them.

How it works and why: strings. The < and > operators compare strings by UTF-16 code units character by character and not by the «alphabet» or by numeric value: '10' < '9' is true because '1' is less than '9'. Capital letters come before lowercase ones. The Ukrainian і, ї, є, ґ have codes outside the main а-я range, so plain sorting puts them after я. To check the order on a UI you need a language collation:

'B' < 'a';       // true  (UTF-16 code units: 'B' = 66, 'a' = 97)
'10' < '9';       // true  (compared character by character)
'10' < 9;         // false (one side is a number: numeric comparison)

// Cyrillic: і, ї, є, ґ stand outside alphabetical order
['я', 'є', 'а', 'і', 'ґ'].sort();
// ['а', 'я', 'є', 'і', 'ґ']
['я', 'є', 'а', 'і', 'ґ'].sort((a, b) => a.localeCompare(b, 'uk'));
// ['а', 'ґ', 'є', 'і', 'я']

const natural = new Intl.Collator('uk', { numeric: true });
['file10', 'file2', 'file1'].sort(natural.compare);   // file1, file2, file10

localeCompare(b, 'uk') and Intl.Collator use the rules of the language (the numeric: true option gives «natural» sorting of files). It matters that the expected order in the test is built with the same locale as on the page, otherwise a mismatch appears between environments with different ICU data.

Sorting. Array.prototype.sort() without a comparator sorts elements as strings and changes the array in place. There is also a side effect: if the array is shared between tests (a fixture, a constant) the order changes for everyone. toSorted returns a new array (the ES2023 library is needed: target or lib no lower than ES2023):

[10, 1, 2].sort();                  // [1, 10, 2]  (as strings)
[10, 1, 2].sort((a, b) => a - b);   // [1, 2, 10]

const amounts = [3, 1, 2];
const sorted = amounts.toSorted((a, b) => a - b);   // ES2023: new array
// amounts is still [3, 1, 2]

Dates. Months in Date are numbered from zero. A string with only a date is parsed as UTC and one with a date and time without a zone as local time: the same «15 January» becomes different instants depending on the notation. Overflow silently shifts the date:

new Date(2026, 0, 15);              // the month is zero-based: 15 January, local time
new Date('2026-01-15');             // date only: this is UTC 00:00
new Date('2026-01-15T10:00');       // date and time without a zone: local time
new Date('2026-01-15T10:00Z');      // with Z: UTC

const d = new Date(2026, 0, 31);
d.setMonth(1);                      // there is no 31 February: it overflows to 3 March

Methods such as getDate() return the local day, so a test that works in Kyiv fails on CI in UTC around midnight:

// in Kyiv in winter (UTC+2) this is already 15 January, in UTC still 14 January
const created = new Date('2026-01-14T23:30:00Z');
created.getDate();                  // 15 in Kyiv, 14 on CI in UTC

// playwright.config.ts: fixes the browser zone
use: { timezoneId: 'Europe/Kyiv', locale: 'uk-UA' }

Rules: exchange dates in ISO 8601 with Z or an offset, fix the zone (the TZ variable for the Node process on CI, while timezoneId in Playwright affects only the browser and not the Node code of the test), use a library for calendar arithmetic (date-fns, Luxon) and control the current time in tests through page.clock. The new Temporal API removes many of these problems but its availability depends on the runtime, so check it before using.

Mutations and copies. Objects and arrays are passed by reference. Spread ({ ...obj }, [...arr]) makes a shallow copy: the top level is new and the nested objects are shared.

A copy of test data

Wrong

Spread for nested data

copy.meta.tags.push() changes the original as well. One test corrupts the data of the next and the failure depends on the order.

Right

structuredClone or a factory

A deep copy is independent. Even better is to hand out data through a factory function that creates a fresh object every time.

Figure 1. Shared test data must be either immutable or handed out anew for each test.
const base = { amount: 100, meta: { tags: ['a'] } };
const shallow = { ...base };
shallow.meta.tags.push('b');       // base.meta.tags changed as well

const deep = structuredClone(base);
deep.meta.tags.push('c');          // base is untouched

structuredClone is available in Node since 17 and in all modern browsers, but it has limits:

structuredClone({ run() {} });          // DataCloneError: run() {} could not be cloned
structuredClone(new Account());         // the class prototype is lost: a plain object
structuredClone({ d: new Date(0) });    // Date, Map, Set are preserved

JSON.parse(JSON.stringify({ d: new Date(0), u: undefined, n: NaN }));
// { d: '1970-01-01T00:00:00.000Z', n: null }  (Date became a string, undefined vanished)

JSON.parse(JSON.stringify(x)) is worse: it loses undefined, turns Date into a string, NaN and Infinity into null and throws on BigInt.

Common mistakes.

  • arr.sort() without a comparator for numbers: [10, 1, 2] becomes [1, 10, 2].
  • Sorting a shared array from a fixture in place: the order changes in all tests of the worker.
  • Comparing Ukrainian strings through < or sort(): «і», «ї», «є», «ґ» stand in the wrong place.
  • A month without accounting for zero and a date without a zone: an error of a month or a day depending on the environment.
  • Spread instead of a deep copy for nested data: tests corrupt each other.

Check yourself

A test on a laptop in Kyiv checks that new Date('2026-03-10T23:30:00Z').getDate() equals 11 and passes. On CI in UTC it fails. Why and how to make the result the same?

Answer

getDate() returns the day in the local zone: in Kyiv (UTC+2) it is already 11 March and in UTC still the 10th. Fix the zone (TZ for the Node process on CI) or use UTC methods (getUTCDate()) or explicit Intl.DateTimeFormat formatting with timeZone.

A fixture exports const PRICES = [30, 5, 100] and one test calls PRICES.sort(). What happens to other tests of the same worker?

Answer

sort() changes the array in place and also sorts as strings: it becomes [100, 30, 5] for everyone who reads the constant after this test. Tests begin to depend on execution order. Use toSorted((a, b) => a - b) or a copy [...PRICES].sort(...) and make the constant itself readonly.

In an interview. Junior: sort() without a comparator sorts as strings and mutates the array, so I pass a comparator or use toSorted. Months in Date are zero-based and spread makes only a shallow copy, for a deep one I use structuredClone. Middle/Senior: I compare Ukrainian strings with localeCompare or Intl.Collator of the same locale as on the page. I exchange dates in ISO 8601 with a zone, fix TZ for Node on CI and timezoneId for the browser and control time through page.clock. I make shared data immutable or hand it out from a factory and I know the limits of structuredClone (functions, prototypes).

More articles in this chapter