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 (32)
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
You make a solid point about prioritizing readability in code—after all, maintainability and clarity are crucial. However, one-liners can still have their place, especially for small utilities where they condense repetitive patterns into a concise format. That said, the key is balance—if a one-liner sacrifices readability or debug-ability, it's better to go with the "trad" approach.
For something like the debounce example, I agree it might look dense. Wrapping it in a helper function or using a library can make it more readable while keeping the functionality intact.
At the end of the day, code should be optimized for the reader, not just the writer. So, I totally see where you're coming from—thanks for the feedback!
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"
Totally agree—just because it can be written in one line doesn’t mean it should! 😊 Readability and maintainability should always come first, especially when working in a team. White space is free, and clarity often trumps cleverness in the long run.
For object cloning, just use the built in
structuredClone
functionYou're absolutely right—structuredClone is a great built-in option for deep cloning objects, and it's much more robust than some common alternatives like JSON.parse(JSON.stringify), especially when dealing with complex data (e.g., circular references, Date objects)
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.Some 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.
That's a valid point—edge cases like escaped or quoted commas can definitely break simplistic CSV parsing implementations. In real-world scenarios, you're better off using a battle-tested library like PapaParse or leveraging built-in solutions if available in your environment. These tools handle edge cases, special characters, and larger datasets much more reliably than DIY code.
The examples are more about showcasing concepts, but you're absolutely right that for production use, libraries are often the safer and more efficient choice. Thanks for pointing that out!
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 😅Thank you for such a thoughtful and constructive comment! You bring up an excellent point—what may look "cool" at first glance can often lead to complexity, especially when debugging or maintaining the code later. The goal should always be clarity first, efficiency second, and striking that balance is something I’m continually working on.
I truly appreciate your perspective and kind words—it’s a reminder that growth as a developer is a journey, and feedback like this plays a huge role in it. I'll definitely consider writing a follow-up article addressing these points, as I believe it’s essential to evolve based on insights from more experienced developers. Thanks again for sharing your thoughts and encouragement! 😊
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 worsened, and one-liners often sacrifice error checking and edge cases to reasonably fit on one line.
And of course, use
structuredClone
, not parse(stringify()).Absolutely agree—conciseness should never come at the cost of readability or maintainability. One-liners can be clever, but they often make debugging harder, reduce clarity, and as you mentioned, skip over critical aspects like error handling and edge cases.
Also, structuredClone is definitely the way to go for object cloning when supported—it's safer and more reliable than JSON.parse(JSON.stringify) for modern JavaScript. Thanks for highlighting these important points—it’s a great reminder to write code that prioritizes maintainability over cleverness!
Well, putting everything on one line sure does make it a 'one-liner' ;)
Still, thanks for pointing to some usefull API's.
Haha, fair point—turning everything into a "one-liner" is certainly one way to meet the definition! 😊 But jokes aside, the goal was to showcase some useful modern APIs and techniques, not necessarily to advocate for condensing everything into a single line.
Thanks for the feedback—glad you found the APIs useful! It’s all about finding the right balance between readability and efficiency.
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.Great point—using .flat(Infinity) is powerful for deeply nested arrays, but it definitely comes with risks, especially with circular references. As you demonstrated, attempting to flatten a structure with circular dependencies will throw a RangeError, making it critical to handle or prevent such cases.
A safer approach could involve validating the input structure first or implementing custom logic with a Set to track visited nodes and avoid infinite loops. While .flat() is handy, knowing its limitations helps ensure more robust code. Thanks for pointing this out!
In the frontend i would debounce with requestAnimationFrame...
Using requestAnimationFrame for debouncing in the frontend is an interesting approach, especially for tasks tied to visual updates, like resizing or scrolling. It ensures the logic runs in sync with the browser's rendering cycle, making it more efficient for UI-related tasks.
That said, for other scenarios like API calls or more general-purpose debouncing, a timed approach (e.g., setTimeout) might still be the better fit. It’s all about picking the right tool for the job—thanks for bringing up this technique!
The
JSON
technique is not only slow because of the double-pass processing, it is also fraught with hazards. Check the exceptions that can be thrown: