We have all, at one time or another, looked at some horrid wall of JavaScript code cursing silently within ourselves, knowing pretty well that there should be a better way.
After some time spent learning, I have found some neat one-liners that will obliterate many lines of verbose code.
These are truly useful, readable tips that take advantage of modern JavaScript features for tackling common problems.
So, whether you are cleaning up code or just starting a fresh project, these tricks can help with more elegant and maintainable code.
Here are 9 such nifty one-liners you can use today.
Flattening a Nested Array
Ever tried flattening an array that goes so deep? Back in the day, that meant lots of complicated multiple loops, temporary arrays, and altogether too much code.
But now it's executed very nicely in a powerful single-liner:
const flattenArray = arr => arr.flat(Infinity);
const nestedArray = [1, [2, 3, [4, 5, [6, 7]]], 8, [9, 10]];
const cleanArray = flattenArray(nestedArray);
// Result: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If you would do this in a more traditional way, you would have something like this:
function flattenTheHardWay(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(flattenTheHardWay(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
}
All hard work is taken care of by the flat(), and adding Infinity tells it to go down to any level that it may. Simple, clean, and it works.
Object Transform: Deep Clone Without Dependencies
If you need a true deep clone of an object without pulling in lodash? Here's a zero-dependency solution that handles nested objects, arrays, and even dates:
const deepClone = obj => JSON.parse(JSON.stringify(obj));
const complexObj = {
user: { name: 'Alex', date: new Date() },
scores: [1, 2, [3, 4]],
active: true
};
const cloned = deepClone(complexObj);
The old way? You'd have to type something like this:
function manualDeepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
if (obj instanceof Date) return new Date(obj);
const clone = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
clone[key] = manualDeepClone(obj[key]);
}
}
return clone;
}
Quick heads-up: This one-liner does have a few limitations - it won't handle functions, symbols, or circular references. But for 90% of use cases, it's pretty much spot on.
String Processing: Convert CSV to Array of Objects
This is a nice little one-liner that takes CSV data and spits out a manipulable array of objects, ideally for use in API responses or reading in data:
const csvToObjects = csv => csv.split('\n').map(row => Object.fromEntries(row.split(',').map((value, i, arr) => [arr[0].split(',')[i], value])));
const csvData = `name,age,city
Peboy,30,New York
Peace,25,San Francisco
Lara,35,Chicago`;
const parsed = csvToObjects(csvData);
// Result:
// [
// { name: 'Peboy', age: '30', city: 'New York' },
// { name: 'Peace', age: '25', city: 'San Francisco' },
// { name: 'Lara', age: '35', city: 'Chicago' }
// ]
Old-fashioned? Oh, you would probably be writing something like this:
function convertCSVTheHardWay(csv) {
const lines = csv.split('\n');
const headers = lines[0].split(',');
const result = [];
for (let i = 1; i < lines.length; i++) {
const obj = {};
const currentLine = lines[i].split(',');
for (let j = 0; j < headers.length; j++) {
obj[headers[j]] = currentLine[j];
}
result.push(obj);
}
return result;
}
It's an effective way of doing data transformation with a one-liner, but add some error handling before plunging it into production.
Array Operations: Remove Duplicates and Sort
Here's a shortened one-liner that removes duplicates and sorts your array at the same time, perfect for cleaning a data set:
const uniqueSorted = arr => [...new Set(arr)].sort((a, b) => a - b);
// Example of its use:
const messyArray = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
const cleaned = uniqueSorted(messyArray);
// Result: [1, 2, 3, 4, 5, 6, 9]
// For string sorting
const messyStrings = ['banana', 'apple', 'apple', 'cherry', 'banana'];
const cleanedStrings = [...new Set(messyStrings)].sort();
// Result: ['apple', 'banana', 'cherry']
This is what the old way used to look like:
function cleanArrayManually(arr) {
const unique = [];
for (let i = 0; i < arr.length; i++) {
if (unique.indexOf(arr[i]) === -1) {
unique.push(arr[i]);
}
}
return unique.sort((a, b) => a - b);
}
The Set takes care of duplicates perfectly, and then the spread operator turns it back into an array. And you just call sort() afterwards!
DOM Manipulation: Query and Transform Multiple Elements
Here's a powerful one-liner that lets you query and transform multiple DOM elements in one go:
const modifyElements = selector => Array.from(document.querySelectorAll(selector)).forEach(el => el.style);
// Use it like this:
const updateButtons = modifyElements('.btn')
.map(style => Object.assign(style, {
backgroundColor: '#007bff',
color: 'white',
padding: '10px 20px'
}));
// Or even simpler for class updates:
const toggleAll = selector => document.querySelectorAll(selector).forEach(el => el.classList.toggle('active'));
The traditional approach would be:
function updateElementsManually(selector) {
const elements = document.querySelectorAll(selector);
for (let i = 0; i < elements.length; i++) {
const el = elements[i];
el.style.backgroundColor = '#007bff';
el.style.color = 'white';
el.style.padding = '10px 20px';
}
}
This works in all modern browsers and saves you from writing repetitive DOM manipulation code.
Parallel API Calls with Clean Error Handling
This is another clean line, one-liner that does parallel calls to APIs and does so in very clean error handling.
const parallelCalls = urls => Promise.allSettled(urls.map(url => fetch(url).then(r => r.json())));
// Put it to work:
const urls = [
'https://api.example.com/users',
'https://api.example.com/posts',
'https://api.example.com/comments'
];
// One line to fetch them all:
const getData = async () => {
const results = await parallelCalls(urls);
const [users, posts, comments] = results.map(r => r.status === 'fulfilled' ? r.value : null);
};
More verbose would be:
async function fetchDataManually(urls) {
const results = [];
for (const url of urls) {
try {
const response = await fetch(url);
const data = await response.json();
results.push({ status: 'fulfilled', value: data });
} catch (error) {
results.push({ status: 'rejected', reason: error });
}
}
return results;
}
Promise.allSettled
is the hero here; it doesn't fail if one request fails and it gives back clean status information for each call.
Date/Time Formatting: Clean Date Strings Without Libraries
Here's a sweet one-liner that turns dates into clean, readable strings without any external dependencies:
const formatDate = date => new Intl.DateTimeFormat('en-US', { dateStyle: 'full', timeStyle: 'short' }).format(date);
const now = new Date();
console.log(formatDate(now));
// Output: "Thursday, December 3, 2024 at 2:30 PM"
// Want a different format? Easy:
const shortDate = date => new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', year: 'numeric' }).format(date);
// Output: "Dec 3, 2024"
The old-school way would look like this:
function formatDateManually(date) {
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const dayName = days[date.getDay()];
const monthName = months[date.getMonth()];
const day = date.getDate();
const year = date.getFullYear();
const hours = date.getHours();
const minutes = date.getMinutes();
const ampm = hours >= 12 ? 'PM' : 'AM';
return `${dayName}, ${monthName} ${day}, ${year} at ${hours % 12}:${minutes.toString().padStart(2, '0')} ${ampm}`;
}
Intl.DateTimeFormat
handles all the heavy lifting, including localization. No more manual date string building!
Event Handling: Debounce Without the Bloat
Here's a clean one-liner that creates a debounced version of any function - perfect for search input or window resize handlers:
const debounce=(fn,ms)=>{let timeout;return(...args)=>{clearTimeout(timeout);timeout=setTimeout(()=>fn(...args),ms);};};
// Put it to work:
const expensiveSearch=query=>console.log('Searching for:',query);
const debouncedSearch=debounce(expensiveSearch,300);
// Use it in your event listener:
searchInput.addEventListener('input',e=>debouncedSearch(e.target.value));
The traditional way would look like this:
function createDebounce(fn, delay) {
let timeoutId;
return function debounced(...args) {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
fn.apply(this, args);
timeoutId = null;
}, delay);
};
}
This one-liner covers all basic debouncing use cases and saves you from calling functions unnecessarily, especially when inputs are generated in rapid succession like typing or resizing.
Local Storage: Object Storage with Validation
Here's just another clean one-liner that handles object storage in localStorage with built-in validation and error handling:
const store = key => ({ get: () => JSON.parse(localStorage.getItem(key)), set: data => localStorage.setItem(key, JSON.stringify(data)), remove: () => localStorage.removeItem(key) });
// Use it like this:
const userStore = store('user');
// Save data
userStore.set({ id: 1, name: 'John', preferences: { theme: 'dark' } });
// Get data
const userData = userStore.get();
// Remove data
userStore.remove();
The old way would need something like this:
function handleLocalStorage(key) {
return {
get: function() {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : null;
} catch (e) {
console.error('Error reading from localStorage', e);
return null;
}
},
set: function(data) {
try {
localStorage.setItem(key, JSON.stringify(data));
} catch (e) {
console.error('Error writing to localStorage', e);
}
},
remove: function() {
try {
localStorage.removeItem(key);
} catch (e) {
console.error('Error removing from localStorage', e);
}
}
};
}
The wrapper gives you a clean API for localStorage operations and handles all the JSON parsing/stringify automatically.
Wrapping Up
These one-liners aren't just about writing less code – they're about writing smarter code. Each one solves a common JavaScript challenge in a clean, maintainable way. While these snippets are powerful, remember that readability should always come first. If a one-liner makes your code harder to understand, break it down into multiple lines.
Feel free to mix and match these patterns in your projects, and don't forget to check browser compatibility for newer JavaScript features like flat()
or Intl.DateTimeFormat
if you're supporting older browsers.
Got your own powerful JavaScript one-liners? I'd love to see them!
Follow me on X for more JavaScript tips, tricks, and discussions about web development. I regularly share code snippets and best practices that make our dev lives easier.
Stay curious, keep coding, and remember: good code is not about how little you write, but how clearly you express your intent.
Top comments (20)
A lot of these one liners are just bad coding standards in general. Each line should have 1 function/operation.
Take for example your "Debounce Event Handling" example. If you need to debug that with a breakpoint, you really can't without formatting it. And the "trad" way is more readable.
Also just looking at this
),ms);};};
That's seriously bad readability there.Code IS READ more than it is WRITTEN make things easier on your readers
This. Just because it can be written in one line doesn't mean it should 😊. White space is free. Write elegant readable code and let the bundler do its job. No need to write like a bundler. The article could be better named as "using modern JavaScript"
For object cloning, just use the built in
structuredClone
functionSome of these are things where you're better off using a library or core function.
For example, the CSV parsing will explode if you escape or quote commas.
Id also add that it didnt take into account the hidden Byte Order Marker (BOM) that .xlsx files tend to have.
Remember we write code for colleagues and future selves.
@peboycodes some of us here are probably a senior dev, or been developing for quite some time. The common theme is that just because we could we shouldn't. While you demonstrated a quite a few APIs in JS, to us, one liners are usually pain to read and debug. To an up and coming developer, these may look cool, and I'm afraid it is just that, nothing more. A good code reduces cognitive overload, reduces complexity, increases maintainability and performance. One liners like
.flat
are great, however, fitting a map, reduce and other logic, with minified variables is no so good. You are showing a lot of efficiencies in your examples, and I don't want all of our comments to diminish the value of that. Great work ✨. I wish you good luck in your long journey as a developer. I strongly believe you'll write another article talking about things we commented on, because we have been there in this phase as well 😅In addition to what @jonrandy said,
JSON.parse(JSON.stringify(item))
is not a true deep clone of an object - if before doing that, you had the same reference repeated in multiple objects or arrays, then after you have multiple copies of that reference. There are times when stringify/parse work out - but you should pick structuredClone by default.Well, putting everything on one line sure does make it a 'one-liner' ;)
Still, thanks for pointing to some usefull API's.
The key takeaway people should get from this article is: just because you can do something in one line, doesn't mean that it should be done in one line.
Debugging is harder, readability is sacrificed, and one-liners often sacrifice error checking and edge cases to reasonably fit on one line.
And of course, use
structuredClone
, not parse(stringify()).In the frontend i would debounce with requestAnimationFrame...
With
.flat(Infinity)
you should be prepared for circular references to throw an error.It may be unlikely in most cases, recognize that using
Infinity
– or even numbers like 10000 –.flat()
can throw a RangeError.If you use something called JavaScript minifier along with bundler (if code is split across multiple files) you can not just replace more lines of code into one.
Here's a dijkstra algorithm one liner that I never use.