The string pizza plus a pizza emoji drawn unit by unit: the emoji takes 2 UTF-16 code units. split('').reverse().join('') returns 2 broken halves before azzip; spread keeps the code points; Intl.Segmenter keeps graphemes but took 52 times as long as split.

JavaScript one-liners that stay readable and correct, shown beside the input that breaks each one

Five common one-liners, each printed next to the input that breaks it and the longer form that survives, with Node.js timings so speed stops being a guess.

When are JavaScript one-liners worth writing?#

A JavaScript one-liner is worth writing when it reads as plainly as the loop it replaces and stays correct on the input that breaks it, such as an emoji, '42px' or 2 equal objects. So there are two tests: can a teammate read it at a glance, and does it survive the odd input? Code golf rewards one line JS, while code review rewards a line a teammate can trust.

Most lists of one line JavaScript tricks stop at the clever form and never show it failing. Instead, every section below prints the case that breaks it, taken from a real run. For example, MDN's destructuring page says it is "possible to unpack values from arrays, or properties from objects, into distinct variables". That is why the swap reads so well, and why speed comes third, only when measured.

Which JavaScript one-liners are actually faster when measured?#

In a Node.js 18 benchmark run on 6 October 2026, the Set dedupe was 31.6 times faster than filter plus indexOf, while the destructuring swap ran 2.3 times slower than a temp variable. So shorter is not the same as faster, and only a benchmark can tell them apart.

Show data table
the slower form divided by the faster one, median of 7 rounds. Source: Atyantik benchmark, Node.js v18.20.4, 6 October 2026
Item Value
filter + indexOf versus Set 31.6
reduce + concat versus flat(Infinity) 4.4
destructuring swap versus temp variable 2.3
spread reverse versus split reverse 1.2

Only the Set dedupe gap is large; the swap and reverse gaps are small.

How many times slower the slower form divided by the faster one, median of 7 rounds. Source: Atyantik benchmark, Node.js v18.20.4, 6 October 2026 Atyantik benchmark run on Node.js v18.20.4, 6 October 2026

In particular, the big gap comes from the algorithm, not the syntax. In that 6 October 2026 test, the array held 10,000 numbers with 1,000 distinct values. There, filter plus indexOf took a median 2.29 milliseconds. That is because indexOf rescans the array for every item. In the same 6 October 2026 test, the Set took 0.072 milliseconds on that array. Meanwhile, the swap gap is real but tiny, at 0.62 against 0.27 nanoseconds per swap. So it only matters inside a very hot loop that runs millions of times.

Your array, deduped two ways

Set the array length and how many distinct values it holds; it estimates the time for a Set dedupe and for filter plus indexOf, and the ratio between them.

Your array

an assumption, change it

Scales the 6 October 2026 Node.js 18 timings linearly: 7.248 ns per item for the Set, 0.2291 ns per item per distinct value for indexOf.

Times slower, filter plus indexOf

31.6

Set dedupe, microseconds
72.5
filter plus indexOf, microseconds
2,291

Arithmetic from the Atyantik benchmark (6 October 2026). Modelled, not measured.

How do you flatten an array in JavaScript, and what does flat() depth do?#

To flatten an array in JavaScript, call arr.flat(Infinity); a bare flat() flattens only 1 level, so deeper arrays survive inside the result. MDN's flat() page defines the argument as "The depth level specifying how deep a nested array structure should be flattened". And it defaults to 1.

js
[1, [2, [3, [4]]]].flat();         // [1, 2, [3, [4]]]  nested arrays survive
[1, [2, [3, [4]]]].flat(Infinity); // [1, 2, 3, 4]
[1, , 3].flat();                   // [1, 3]  the empty slot is gone

The same MDN page notes that the "flat() method removes empty slots if the array being flattened is sparse". So the length can change too. Therefore, pass the depth on purpose, which costs nothing because flat() is also the fast path. In our 6 October 2026 test, it ran 4.4 times faster than a recursive reduce with concat.

Flattening a 1,000 by 10 nested array4.4 times faster

1,822,116 ns

arr.flat(Infinity)

8,030,150 ns

recursive reduce + concat

The depth argument is also the fast path.

Show data table
Flattening a 1,000 by 10 nested array (nanoseconds per call, median of 7 rounds)
Optionnanoseconds per call, median of 7 rounds
arr.flat(Infinity)1,822,116 ns
recursive reduce + concat8,030,150 ns

Source: Atyantik benchmark, Node.js v18.20.4, 6 October 2026

How does destructuring in JavaScript work, and how do you swap two variables in one line?#

Destructuring in JavaScript unpacks values from arrays or properties from objects into variables, so [a, b] = [b, a] swaps two values without a temp variable. MDN says two values can be "swapped in one destructuring expression". That makes it the clearest swap in JS to read.

js
let a = 1, b = 2;
[a, b] = [b, a];               // a = 2, b = 1
const { size = 1 } = { size: null };
console.log(size);             // null, not 1

But the default value is a trap. MDN's page says a default is used only when the value is undefined, so null passes straight through. In practice, check for null yourself, or add a nullish fallback right after the destructure.

Speed rarely decides this choice for the swap. In our 6 October 2026 test, the destructuring swap took 0.62 nanoseconds and the temp variable took 0.27. So keep the swap for clarity, and switch only inside a loop you have measured.

Show data table
median of 7 rounds, 10 million swaps per round. Source: Atyantik benchmark, Node.js v18.20.4, 6 October 2026
Item Value
[a, b] = [b, a] 0.62
temp variable 0.27

The temp variable is faster, by a third of a nanosecond per swap.

Nanoseconds per swap median of 7 rounds, 10 million swaps per round. Source: Atyantik benchmark, Node.js v18.20.4, 6 October 2026 Atyantik benchmark run on Node.js v18.20.4, 6 October 2026

How does a JavaScript Set remove duplicates, and why does it fail on objects?#

A JavaScript Set keeps one copy of each primitive value, so [...new Set(arr)] dedupes numbers and strings, but 2 objects with equal fields stay 2 entries. MDN's Set page says "Value equality is based on the SameValueZero algorithm". But objects "are compared by reference, not by value."

js
[...new Set([1, 1, NaN, NaN])];          // [1, NaN]
[...new Set([{ id: 1 }, { id: 1 }])];    // still 2 objects
const unique = [...new Map(users.map((u) => [u.id, u])).values()];

So sets in JavaScript are the right JS unique tool for primitives only. For objects, key a Map by the field that defines sameness, as the last line does. Because a Map overwrites, it keeps the last object for each id. And for primitives the Set is also the fast path by a wide margin. In our 6 October 2026 test, it beat filter plus indexOf by 31.6 times on 10,000 numbers.

Deduping 10,000 numbers with 1,000 distinct31.6 times faster

72,478 ns

[...new Set(arr)]

2,291,134 ns

filter + indexOf

The Set wins because indexOf rescans the array for every item.

Show data table
Deduping 10,000 numbers with 1,000 distinct (nanoseconds per call, median of 7 rounds)
Optionnanoseconds per call, median of 7 rounds
[...new Set(arr)]72,478 ns
filter + indexOf2,291,134 ns

Source: Atyantik benchmark, Node.js v18.20.4, 6 October 2026

Which string to number one-liner is correct: unary plus, Number() or parseInt()?#

Unary plus and Number() convert the whole string and return 0 for an empty one, while parseInt() reads digits until the first invalid character, so '42px' gives 42. MDN's parseInt page says it "parses a string argument and returns an integer of the specified radix".

js
+'';               // 0      parseInt('', 10)     -> NaN
+'42px';           // NaN    parseInt('42px', 10) -> 42
+'1e3';            // 1000   parseInt('1e3', 10)  -> 1
+'0x1A';           // 26     parseInt('0x1A', 10) -> 0
+null;             // 0      parseInt(null, 10)   -> NaN

As a result, each row above disagrees, yet each answer is right for some input. For example, a form field that may be blank needs parseInt or an empty check. That is because unary plus turns blank into 0. However, speed is no reason to choose one form over another. In our 6 October 2026 test, all three took between 2.22 and 2.54 nanoseconds.

Show data table
median of 7 rounds; the gap is a third of a nanosecond. Source: Atyantik benchmark, Node.js v18.20.4, 6 October 2026
Item Value
+s 2.22
Number(s) 2.54
parseInt(s, 10) 2.23

All three conversions cost the same; choose by input, not speed.

Nanoseconds per conversion median of 7 rounds; the gap is a third of a nanosecond. Source: Atyantik benchmark, Node.js v18.20.4, 6 October 2026 Atyantik benchmark run on Node.js v18.20.4, 6 October 2026

Why does split('').reverse().join('') break emoji, and what reverses a string safely?#

split('') cuts a string into UTF-16 code units, so an emoji stored as 2 units is reversed into 2 broken halves; spread keeps code points and Intl.Segmenter keeps graphemes. MDN's split page says an empty separator splits "by UTF-16 code units", not by user-perceived characters.

js
'pizza🍕'.split('').reverse().join(''); // broken halves, then 'azzip'
[...'pizza🍕'].reverse().join('');      // '🍕azzip'
[...'👍🏽ok'].reverse().join('');        // 'ko🏽👍'  skin tone split off

In contrast, spread fixes the pizza but not the thumbs up, because a skin tone is a second code point. Only grapheme segmentation keeps it whole, through Intl.Segmenter. But that safety has a real cost in time. In our 6 October 2026 test, grapheme reversal of a 1,000 character string took 52 times as long as split.

Show data table
median of 7 rounds, 1,000 character string. Source: Atyantik benchmark, Node.js v18.20.4, 6 October 2026
Item Value
split('').reverse().join('') 8,732.14
[...s].reverse().join('') 10,332.45
Intl.Segmenter graphemes 457,742.65

Grapheme safety costs 52 times the time of split.

Nanoseconds per reversal median of 7 rounds, 1,000 character string. Source: Atyantik benchmark, Node.js v18.20.4, 6 October 2026 Atyantik benchmark run on Node.js v18.20.4, 6 October 2026

How do you write a one line if in JavaScript without an else?#

A one line if in JavaScript is if (ok) run(); a ternary always needs both branches, so cond && run() is the short form without an else. A JavaScript ternary operator without else does not exist. So a JS one line if, or a JavaScript short if, means one of these three forms.

js
if (ok) run();                         // the plain one line if
ok && run();                           // short form, side effect only
const label = ok ? 'Saved' : 'Draft';  // a value with two branches
0 && 'shown';                          // 0, which React renders

The usual JavaScript one liner if, written as cond ? run() : null, works but says nothing an if would not. Also, MDN's Logical AND page says && returns "the value of the first falsy operand". That is why a count of 0 appears on screen. So the one line if JS developers reach for first should be the plain if.

Ternaries chain because MDN says the operator "is right-associative". When a grade ladder of three ternaries runs, it still returns the right letter. But it takes a slow second read to check. So stop at two levels, and move a longer ladder into a lookup object.

Which MDN pages settle a one-liner before it ships?#

Before a one-liner ships, 4 MDN pages settle most disputes: Array flat() for depth, Set for equality, parseInt for parsing rules and String for UTF-16. Check them in this order during a code review:

  • Array.prototype.flat(): the depth defaults to 1, Infinity flattens all, and empty slots are removed.
  • Set: SameValueZero for primitives, reference equality for objects.
  • parseInt(): the radix, and parsing stops at the first invalid character.
  • String: strings are UTF-16 code units, and emoji are surrogate pairs.
  • Node.js perf_hooks: performance.now() for timing a claim before believing it.

Which MDN page settles which one-liner dispute. Source: MDN Web Docs, read October 2026.

One-linerThe disputeMDN page
arr.flat()How deep does it flatten?Array.prototype.flat()
[...new Set(arr)]Are equal objects deduped?Set
+s or parseInt(s, 10)What happens to '42px'?parseInt()
split('').reverse()What happens to an emoji?String

Source: MDN Web Docs, read October 2026.

What do the safe versions look like in code?#

The safe versions fit in 6 short functions: flatten with a depth, swap, dedupe by key, toNumber by input, reverse by grapheme and a performance.now timer. Then paste them into a utility module and run the timer on your own data.

js
import { performance } from 'node:perf_hooks';
// 1. Flatten with an explicit depth.
export const flatten = (arr, depth = Infinity) => arr.flat(depth);
// 2. Swap two items in an array.
export const swap = (arr, i, j) => { [arr[i], arr[j]] = [arr[j], arr[i]]; return arr; };
// 3. Dedupe objects by a key; the last one wins.
export const uniqueBy = (items, key) => [...new Map(items.map((x) => [x[key], x])).values()];
// 4. Convert by the input you accept.
export const toNumber = (s, { allowUnits = false } = {}) =>
  s == null || String(s).trim() === '' ? NaN : allowUnits ? parseInt(s, 10) : Number(s);
// 5. Reverse by what a person sees as a character.
export const reverse = (s) =>
  [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(s)]
    .map((g) => g.segment).reverse().join('');
// 6. Time a case: the median of several rounds, in milliseconds.
export const time = (fn, rounds = 7) => {
  const t = [];
  for (let r = 0; r < rounds; r++) { const t0 = performance.now(); fn(); t.push(performance.now() - t0); }
  return t.sort((x, y) => x - y)[Math.floor(rounds / 2)];
};

When is a one-liner the wrong tool?#

A one-liner is the wrong tool when it needs a comment to explain, nests more than 2 ternaries, or hides a side effect inside a map or an && chain. Each of these signs points to a better tool. First, a line that needs a comment wants a named function, because the name is the comment. Second, a ternary ladder wants a lookup object or a plain if chain. Finally, a side effect inside map wants a for...of loop, since map should return values.

When a one-liner should become something else, and what it should become. Source: the warning signs in this section.

Warning signBetter tool
The line needs a commentA named function
More than 2 nested ternariesA lookup object or a plain if chain
A side effect inside map or an && chainA for...of loop

Illustrative: a summary of the three signs above.

Also, the rules in our JavaScript clean code practices apply to JavaScript one-liners too. In short, write the longer form whenever a debugger step through the short one would be confusing.

Where do these one-liners lead next?#

The 2 tests from the opening, readable and correct on the breaking input, carry over to clean code, newer ECMAScript built-ins and Node.js servers. The ECMAScript 2026 guide covers the newer built-ins behind several of these snippets. Then the Node.js HTTP server post applies the same runtime to real traffic.

Finally, teams that want this review habit can hire JavaScript developers. And a slow path that is real and measured belongs with web performance work. Even so, the MDN pages above are enough on their own to settle any one-liner.

Questions this post answers

When are JavaScript one-liners worth writing?
A JavaScript one-liner is worth writing when it reads as plainly as the loop it replaces and stays correct on the input that breaks it, such as an emoji, '42px' or 2 equal objects.
How do you flatten an array in JavaScript?
To flatten an array in JavaScript, call arr.flat(Infinity); a bare flat() flattens only 1 level, so deeper arrays survive inside the result.
Does a JavaScript Set remove duplicate objects?
A JavaScript Set keeps one copy of each primitive value, so [...new Set(arr)] dedupes numbers and strings, but 2 objects with equal fields stay 2 entries. So sets in JavaScript are the right JS unique tool for primitives only.
Is there a JavaScript ternary operator without else?
A JavaScript ternary operator without else does not exist. A one line if in JavaScript is if (ok) run(); a ternary always needs both branches, so cond && run() is the short form without an else.

Keep reading