Explore these 22 one-liners and use them in your projects!
JavaScript syntax and built-in methods let you reduce some frequently used code to a single line.
Use Intl.Segmenter to reverse
user-perceived characters correctly, including emoji and characters made
from multiple Unicode code points.
const stringReverse = str => [...new Intl.Segmenter(undefined, { granularity: "grapheme" }).segment(str)].map(({ segment }) => segment).reverse().join("");
stringReverse("Welcome to JavaScript 👨👩👧👦"); //👨👩👧👦 tpircSavaJ ot emocleW
The reduce method makes it easy to
calculate the average of an array of numbers. Passing an initial value
prevents reduce from throwing on an
empty array; this function returns
NaN when the array is empty.
const average = arr => arr.length ? arr.reduce((sum, value) => sum + value, 0) / arr.length : NaN;
average([21, 56, 23, 122, 67]); //57.8
const pastWeek = Array.from({ length: 7 }, (_, days) => new Date(Date.now() - 86_400_000 * days));
If you use a plus sign instead of a minus sign, you can create an array
containing the next seven 24-hour intervals. To start from a specific date,
replace Date.now() with that date's
timestamp. Note that 86_400_000 is the number of milliseconds in 24 hours.
Normalize both local calendar dates to UTC before subtracting them. This avoids incorrect results when a daylight-saving time transition makes a local day shorter or longer than 24 hours.
const dayDiff = (date1, date2) => Math.abs(Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate()) - Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate())) / 86_400_000;
dayDiff(new Date("2021-09-30"), new Date("2021-11-06")); //37
Although JavaScript does not provide a built-in capitalization method, you can write your own function to capitalize a string in just one line.
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
capitalize("javascript one-liners are fun!"); //Javascript one-liners are fun!
A JavaScript Set can contain only unique values. You can use this to remove duplicate values from an array. Primitive values are compared by value, while objects are compared by reference, so separate objects with identical contents are not deduplicated.
const removeDuplicates = (arr) => [...new Set(arr)];
removeDuplicates([31, 56, 12, 31, 45, 12, 31]); //[ 31, 56, 12, 45 ]
This is a surprisingly tricky task in JavaScript because binary
floating-point arithmetic can produce unexpected results. Scaling the
absolute value, adding
Number.EPSILON, and restoring the
original sign handles common rounding cases, including negative values. For
financial calculations that require exact decimal arithmetic, use a
dedicated decimal library instead.
const round = (number, precision) => { const factor = 10 ** precision; return Math.sign(number) * Math.round((Math.abs(number) + Number.EPSILON) * factor) / factor; };
round(7.105, 2); //7.11
round(5.955, 2); //5.96
round(-1.005, 2); //-1.01
The crypto.randomUUID() method
generates a cryptographically secure version 4 UUID. It is widely supported
in modern browsers and is available in secure contexts such as HTTPS and
localhost.
const randomID = () => crypto.randomUUID();
randomID(); // '36b8f84d-df4e-4d49-b662-bcde71a8764f'
Because scrollTop may be fractional
while scrollHeight and
clientHeight are rounded, use a
small threshold instead of an exact comparison.
const scrolledToBottom = () => Math.abs(document.documentElement.scrollHeight - document.documentElement.clientHeight - document.documentElement.scrollTop) <= 1;
scrolledToBottom(); // false
Many websites need this behavior, so this function is useful for a dedicated
“Back to top” button. The options form of
scrollTo() makes the movement
smooth.
const toTop = () => window.scrollTo({ top: 0, behavior: "smooth" });
You can show or hide an element by toggling its semantic
hidden attribute without
overwriting its inline
display style.
const toggle = element => element.toggleAttribute("hidden");
If you need to assign a random color to an element, generate an integer from
0x000000 through
0xffffff and use
padStart() to preserve leading
zeroes.
const hexColor = () => `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, "0")}`;
hexColor(); // '#2db8ea'
hexColor(); // '#77dede'
Client-side JavaScript cannot delete
HttpOnly cookies, and deleting a
cookie requires the same path and domain used when it was created. This
one-liner deletes cookies visible to
document.cookie that use the root
path. To clear all cookies reliably, send the
Clear-Site-Data: "cookies" response
header from the server.
const clearCookies = () => document.cookie && document.cookie.split(";").forEach(cookie => document.cookie = `${cookie.split("=")[0].trim()}=; Max-Age=0; path=/`);
This function extracts plain text from an HTML string. It does not sanitize HTML for safe insertion into the current page.
const stripHtml = html => new DOMParser().parseFromString(html, "text/html").body.textContent ?? "";
stripHtml('<h2>Heading</h2><div>Div-block <p>Paragraph</p></div>'); //'HeadingDiv-block Paragraph'
const isDarkMode = window.matchMedia("(prefers-color-scheme: dark)").matches;
This function keeps a number between the specified minimum and maximum
values. It assumes that min is not
greater than max.
const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
clamp(120, 0, 100); //100
clamp(-20, 0, 100); //0
The structuredClone() method
creates a deep copy and supports many built-in types as well as circular
references. It cannot clone functions, DOM nodes, or every host object and
throws DataCloneError for
unsupported values.
const deepClone = value => structuredClone(value);
deepClone({ user: { name: "Alex" }, dates: [new Date()] });
The modern Object.groupBy() method
groups iterable values using the property keys returned by a callback. It
returns an object with a null prototype and keeps references to the original
items rather than cloning them.
const groupBy = (items, property) => Object.groupBy(items, item => item[property]);
groupBy([{ type: "fruit", name: "Apple" }, { type: "vegetable", name: "Carrot" }, { type: "fruit", name: "Pear" }], "type");
//{ fruit: [{...}, {...}], vegetable: [{...}] }
A Map can count values without
converting them into string keys. Objects are counted by reference, just as
they are in a Set.
const countOccurrences = values => values.reduce((counts, value) => counts.set(value, (counts.get(value) ?? 0) + 1), new Map());
countOccurrences(["apple", "pear", "apple"]); //Map(2) { 'apple' => 2, 'pear' => 1 }
Use RegExp.escape() when dynamic
text must be treated as a literal part of a regular expression. This method
is available in current browsers, but applications supporting older browsers
may need a polyfill.
const literalPattern = value => new RegExp(RegExp.escape(value), "u");
literalPattern("file.js").test("Open file.js"); //true
literalPattern("file.js").test("Open fileXjs"); //false
The Intl.ListFormat API joins
values using language-appropriate punctuation and conjunctions instead of
hard-coded commas and words.
const formatList = (items, locale = "ru") => new Intl.ListFormat(locale, { style: "long", type: "conjunction" }).format(items);
formatList(["JavaScript", "HTML", "CSS"]); //'JavaScript, HTML, и CSS'
This Promise-based helper delays the next step inside an
async function. It does not block
the JavaScript thread.
const sleep = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
const showMessageLater = async () => { await sleep(1000); console.log("One second later"); };
This article is based on material by Anjalee Sudasinghe. Issues in the original examples have been corrected, and new snippets have been added.