JS traps: numbers and money, strings, dates, objects and arrays
Floating-point numbers and money
A JS number is a 64-bit double (IEEE 754), so 0.1 + 0.2 gives 0.30000000000000004 and exact equality on fractions breaks. Money is stored as integers in minor units (cents) with the currency's number of decimals in mind: JPY has 0, KWD has 3. Percentages and rates need an explicit rounding rule from the specification, and toFixed rounds the binary value and returns a string.
TypeScript · JS traps
A sum comparison in a test fails on a difference in the 17th decimal place. How to count money in JS?
A test checks a cart total: two items, 0.1 and 0.2, must give 0.3. The check expect(total).toBe(0.3) fails with «Received: 0.30000000000000004». The bug is neither in the application nor in the test but in how JS stores fractional numbers. Someone who does not know this either «cures» the test with rounding in a random place or hides a real rounding defect in the product. This lesson explains where the error comes from, how to store and compare money and what to do with percentages and rates.
How it works and why. A JS number is a 64-bit floating-point number (IEEE 754, double): 52 bits for the significant part (53 bits of precision with the implicit bit), 11 for the exponent and 1 for the sign. The number is stored in binary and a fraction such as 0.1 has no finite binary form, just as 1/3 has none in decimal. So the nearest representable value is stored: in fact 0.1 is about 0.1000000000000000055. The error is small but it does not disappear on addition, it accumulates, and comparison for exact equality breaks. Integers within Number.MAX_SAFE_INTEGER (253 - 1, that is 9007199254740991) are represented exactly, and that is the basis of the approach to money.
Note toFixed: it rounds the exact binary value and not the decimal one you see in the code. So (1.005).toFixed(2) gives '1.00' because the actual value is 1.00499999999999989. Besides, toFixed returns a string, not a number.
Two ways to store an amount
Wrong
100.5 as a fraction
Addition, multiplying by a rate and comparison accumulate error. toBe fails and toBeCloseTo only hides the question of which rounding rule the product uses.
Right
10050 minor units as an integer
Addition and subtraction are exact, comparison through toBe. Fractional arithmetic (percentages, rates) goes to one place with an explicit rounding rule.
Figure 1. Money is stored and compared in minor units and rounded only where the specification demands it.
Example: from fractions to minor units. Rules for working with money in tests:
Store amounts in minor units (kopiykas, cents) as integers: 10050 instead of 100.50.
Know the number of minor units of the currency. Most have 2 but JPY has 0 and KWD has 3 (Intl reports this through resolvedOptions().maximumFractionDigits). Multiplying by a fixed 100 for every currency is a mistake.
Convert the string from an API response to minor units without an intermediate fractional number: Math.round(Number('1.005') * 100) gives 100, not 101.
functiontoMinor(amount: string, digits = 2): number {
const m = /^(-?)(\d+)(?:\.(\d+))?$/.exec(amount);
if (!m) thrownewError('Bad amount: ' + amount);
const frac = m[3] ?? '';
if (frac.length > digits) {
thrownewError('Too many decimals: ' + amount); // no silent rounding
}
returnNumber((m[1] ?? '') + (m[2] ?? '') + frac.padEnd(digits, '0'));
}
toMinor('100.50'); // 10050toMinor('-0.5'); // -50
The function works with a string and refuses extra decimal digits instead of silently rounding: a format mismatch must be visible.
Percentages, rates and the rounding rule. Fractional arithmetic still happens: a 1% fee, a conversion by a rate. Here you must know the rule from the specification because the options give different cents. Banks often apply banker's rounding (half-even): exactly in the middle it rounds to the even number. For 100.5 that is 100, while Math.round gives 101. Also Math.round rounds «up» for negatives: Math.round(-2.5) is -2.
// a 1% fee on 100.50 in minor units: 100.5, exactly in the middleconst fee = (10050 * 100) / 10000;
Math.round(fee); // 101 (half up)roundHalfEven(fee); // 100 (banker's rounding)functionroundHalfEven(x: number): number {
const f = Math.floor(x);
const diff = x - f;
if (diff < 0.5) return f;
if (diff > 0.5) return f + 1;
return f % 2 === 0 ? f : f + 1;
}
For more complex calculations a decimal library (decimal.js, big.js) with an explicit rounding mode is used. What matters is that the expected result in a test comes from the specification and not from the output of the program itself.
// in minor units: integers, exact comparisonexpect(toMinor('0.10') + toMinor('0.20')).toBe(toMinor('0.30'));
// fractional: only with a toleranceexpect(0.1 + 0.2).toBeCloseTo(0.3, 5);
// display: Intl, not string concatenationconst fmt = newIntl.NumberFormat('uk-UA', { style: 'currency', currency: 'UAH' });
fmt.format(1250.5); // '1\u00a0250,50\u00a0₴' (non-breaking spaces)
Limits and alternatives.toBeCloseTo(x, 5) compares with a tolerance of 5 digits and suits fractional quantities that are truly approximate (measurements, load percentages) but not money: there a difference of one cent is a bug. BigInt is needed for integers above 2^53 - 1, for example identifiers or amounts in the smallest units of cryptocurrencies. It does not mix with number in arithmetic and does not serialise to JSON:
10n + 1; // TypeError: Cannot mix BigInt and other types, ...
JSON.stringify({ id: 10n }); // TypeError: Do not know how to serialize a BigInt
Common mistakes.
toBe for fractional sums: the test depends on the order of operations.
toFixed(2) as «rounding money»: it works on the binary value and returns a string.
Fixed multiplication by 100 for any currency: JPY and KWD give an error of 100 times or 10.
Computing the expected value with the same code as the application: the rounding error repeats in both places and the test does not see it.
Mixing BigInt and number in one expression: TypeError.
Check yourself
The specification says a 1% fee on the amount with half-even rounding. For 10050 minor units the application returns 101 and the test expects 100. Who is right and what to check first?
Answer
100.5 lies exactly in the middle, so half-even gives the even 100 and half-up gives 101. If the specification says half-even the application has a defect (Math.round was used). First check what exactly the specification says and only then decide where the bug is.
Why does Math.round(Number('1.005') * 100) give 100 although «1.005» is 100.5 minor units, and how to get an exact result?
Answer
The number 1.005 in binary is slightly less than 1.005, the product with 100 is 100.49999999999999 and rounding goes down. The exact way: work with the string (split into integer and fractional parts) or use a decimal library, and either reject extra digits or round them by an explicit rule.
Related lessons: “Converting strings to numbers”, “Comparison: == and ===, ||, ?? and ?.”, “Strings, dates, mutations and sorting”.
In an interview.Junior:0.1 + 0.2 in JS does not equal 0.3 because of the binary representation of fractions. So I store and compare money as integers in minor units and not as fractions. Middle/Senior: I know that toFixed rounds the binary value and returns a string, that the number of minor units depends on the currency (JPY 0, KWD 3) and that fees and rates must be computed with an explicit rounding rule from the specification (half-even or half-up) through a decimal library. I derive the expected value in a test from the specification and not from the application code.
Converting strings to numbers
Number('') gives 0, not NaN, so an empty amount field is read as zero, while parseInt and parseFloat silently cut the string at a foreign character. A comma is not a decimal separator in Number or parseFloat, and parseInt is always called with radix 10. For UI amounts, write a strict parser: strip spaces and the currency, replace the comma, check the format and return integer minor units.
TypeScript · JS traps
An empty amount field was read as 0 and the test «successfully» checked a zero payment. Where did the zero come from?
The amount field on a form was left empty. The test read its value, converted it through Number(raw) and compared it with zero: the check passed. In reality the empty field should have produced a validation error and the test did not notice because Number('') returns 0 and not NaN. Similar quiet conversions exist in all ways of «making a number from a string» and each one behaves differently. This lesson goes through them together and gives a recipe for reliable reading of amounts from the interface.
How it works and why. There are two families. Number(s) and unary plus apply the specification's conversion to the whole string: they strip whitespace at the edges, treat an empty string as zero and any foreign character gives NaN. parseInt and parseFloat instead read a number from the start of the string and silently drop the rest. That is historically handy for «12px» but dangerous for checks: a partly parsed string looks like a normal number.
String
Number(s)
parseInt(s, 10)
parseFloat(s)
'42'
42
42
42
''
0
NaN
NaN
'12px'
NaN
12
12
'1e3'
1000
1
1000
'1,5'
NaN
1
1
'1 000.50'
NaN
1
1
'0x10'
16
0
0
Other values are surprising too: Number(null) and Number([]) give 0, Number(undefined) gives NaN, Number('1_000') gives NaN and Number(' 42 ') gives 42. A comma is not a decimal separator in either Number or parseFloat, although in a Ukrainian interface it is exactly that.
Example: a zero instead of an error.
const raw = await page.getByTestId('amount').inputValue(); // ''const amount = Number(raw); // 0expect(amount).toBeGreaterThanOrEqual(0); // green
Two ways to read an amount from a field
Wrong
Number(raw) / parseFloat(raw)
An empty field becomes 0, «1 250,50 ₴» becomes 1 or NaN. The test checks not what the user is shown.
Right
A strict format parser
The string is first checked with a regular expression and an unknown format throws an error. The failure appears at the reading place and not on a wrong number later.
Figure 1. A parser must fail on an unexpected format and not return a part of the number.
For amounts from the interface an explicit parser for the specific format is written: remove spaces (including the non-breaking one that Intl.NumberFormat puts between thousands; the \s class in regular expressions covers both U+00A0 and the narrow non-breaking U+202F), the currency sign, change the comma to a dot, check with a regular expression and only then convert. After that take integer minor units (see the previous lesson):
functionparseUiAmount(text: string): number {
const clean = text
.replace(/\s/g, '') // \s also covers non-breaking spaces
.replace(/(₴|UAH)/, '')
.replace(',', '.');
if (!/^-?\d+(\.\d{1,2})?$/.test(clean)) {
thrownewError('Bad amount: ' + text);
}
returntoMinor(clean); // minor units
}
parseUiAmount('1\u00a0250,50 ₴'); // 125050parseUiAmount('12px'); // Error: Bad amount: 12px
A better alternative to parsing: do not convert the output to a number but compare with the expected string formatted by the same Intl.NumberFormat with the needed locale. Then the format is checked the way the user sees it.
map(parseInt) breaks because map passes three arguments to the callback and the second one for parseInt is the radix (radix 1 is invalid, 2 does not fit '3'). So parseInt is always called with an explicit radix of 10. Checking for NaN has its own pitfalls too:
NaN === NaN; // falseNumber.isNaN('abc'); // false: no coercion, 'abc' is not the number NaNisNaN('abc'as any); // true: coerces first (TS2345 without as any)Number.isNaN(Number('abc')); // trueNumber.isFinite('5'); // false: strict, no coercionNumber.isFinite(5 / 0); // false
Limits and alternatives. For values that come from an API a string-to-number conversion is usually not needed: if the contract says «the amount is a string with a decimal fraction» the TS type is declared that way (string) and converted to minor units with a single parser. In schema-based frameworks (zod) there is z.coerce.number(), but it works through Number() and likewise turns an empty string into 0: for amounts your own format check is better. «What the user typed» and «what is shown» should be parsed differently: typed input often contains spaces and separators, the shown value depends on the locale.
Common mistakes.
Number('') and Number(' ') give 0: an empty field is read as a zero amount.
parseInt and parseFloat silently cut the string: «1 250,50 ₴» gives 1.
parseInt without a radix or inside map as a reference: a different radix than expected.
x === NaN is always false; and isNaN('abc') coerces the string first.
A parser that leaves the non-breaking space: the string «1 250» does not match the regular expression because the space is not an ordinary one.
Check yourself
What will Number('12,5'), parseFloat('12,5') and Number('') return and why does it matter for a test of a Ukrainian interface?
Answer
NaN, 12 and 0. The Ukrainian locale shows a decimal fraction with a comma and JS does not consider it a separator: Number gives NaN and parseFloat silently drops the fractional part. An empty string gives 0. So you need your own parser that replaces the comma and checks the format.
Why does ['10', '10', '10'].map(parseInt) return [10, NaN, 2]?
Answer
map passes (value, index) so the second argument of parseInt becomes the radix: 0 (meaning 10), 1 (invalid, gives NaN) and 2 (binary, '10' is 2). The fix: map((s) => parseInt(s, 10)) or map(Number).
Related lessons: “Floating-point numbers and money”, “Comparison: == and ===, ||, ?? and ?.”, “Strings, dates, mutations and sorting”.
In an interview.Junior:Number('') gives zero and parseInt silently cuts the string at the first invalid character. I check NaN with Number.isNaN and call parseInt with radix 10. Middle/Senior: For amounts from the interface I write a strict parser: I remove spaces (the \s class also takes non-breaking ones) and the currency, replace the comma, check with a regular expression and fail on an unknown format, and I hand the result back as integer minor units. Sometimes it is simpler to compare with a string formatted by Intl.NumberFormat of the same locale.
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:
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 bugconst b = response.fee ?? 500; // 0 stays 0const 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; // SyntaxErrorconst 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:
typeBody = { data: { items: { amount: number }[] } };
declare const body: Body;
// weak: passes for [] and when the items field is missing altogetherexpect(body.data?.items?.length).toBeFalsy();
// exact: fails if items is missing and points at the real differenceexpect(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.isexpect(0).toBe(-0); // fails: Object.is(0, -0) is falseexpect(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.
Related lessons: “Converting strings to numbers”, “Floating-point numbers and money”, “Optional, undefined and null”.
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.
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: 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 = newIntl.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:
newDate(2026, 0, 15); // the month is zero-based: 15 January, local timenewDate('2026-01-15'); // date only: this is UTC 00:00newDate('2026-01-15T10:00'); // date and time without a zone: local timenewDate('2026-01-15T10:00Z'); // with Z: UTCconst d = newDate(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 Januaryconst created = newDate('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 wellconst 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 clonedstructuredClone(newAccount()); // the class prototype is lost: a plain objectstructuredClone({ d: newDate(0) }); // Date, Map, Set are preserved
JSON.parse(JSON.stringify({ d: newDate(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.
Related lessons: “readonly and immutability”, “Floating-point numbers and money”, “Converting strings to numbers”.
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).