DEV Community

9 JavaScript One-Liners That Replace 50 Lines of Code

Paul on December 05, 2024

We have all, at one time or another, looked at some horrid wall of JavaScript code cursing silently within ourselves, knowing pretty well that ther...
Collapse
 
gitkearney profile image
Kearney Taaffe

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

Collapse
 
peboycodes profile image
Paul

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!

Collapse
 
gopikrishna19 profile image
Gopikrishna Sathyamurthy

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"

Collapse
 
peboycodes profile image
Paul

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.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

For object cloning, just use the built in structuredClone function

Collapse
 
peboycodes profile image
Paul

You'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)

Collapse
 
miketalbot profile image
Mike Talbot ⭐

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.

Collapse
 
moopet profile image
Ben Sinclair

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.

Collapse
 
peboycodes profile image
Paul

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!

Collapse
 
cptcrunchy profile image
Jason Gutierrez • Edited

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.

Collapse
 
gopikrishna19 profile image
Gopikrishna Sathyamurthy

@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 😅

Collapse
 
peboycodes profile image
Paul

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! 😊

Collapse
 
skhmt profile image
Mike 🐈‍⬛ • Edited

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()).

Collapse
 
peboycodes profile image
Paul

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!

Collapse
 
rvraaphorst profile image
Ronald van Raaphorst

Well, putting everything on one line sure does make it a 'one-liner' ;)
Still, thanks for pointing to some usefull API's.

Collapse
 
peboycodes profile image
Paul

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.

Collapse
 
oculus42 profile image
Samuel Rouse

With .flat(Infinity) you should be prepared for circular references to throw an error.

const a = [];
const b = [a]
a.push(b);
a.flat(Infinity); // RangeError: Maximum call stack size exceeded
Enter fullscreen mode Exit fullscreen mode

It may be unlikely in most cases, recognize that using Infinity – or even numbers like 10000 –  .flat() can throw a RangeError.

Collapse
 
peboycodes profile image
Paul

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!

Collapse
 
retakenroots profile image
Rene Kootstra • Edited

In the frontend i would debounce with requestAnimationFrame...

Collapse
 
peboycodes profile image
Paul

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!

Collapse
 
gilmoretj_tracyg_3999d profile image
gilmoretj (Tracy-G)

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:

Collapse
 
amankrokx profile image
Aman Kumar • Edited

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.

let V=9;function minDistance($,t){let r=Number.MAX_VALUE,e=-1;for(let n=0;n<V;n++)!1==t[n]&&$[n]<=r&&(r=$[n],e=n);return e}function printSolution($){console.log("Vertex         Distance from Source<br>");for(let t=0;t<V;t++)console.log(t+"          "+$[t]+"<br>")}function dijkstra($,t){let r=Array(V),e=Array(V);for(let n=0;n<V;n++)r[n]=Number.MAX_VALUE,e[n]=!1;r[t]=0;for(let o=0;o<V-1;o++){let i=minDistance(r,e);e[i]=!0;for(let l=0;l<V;l++)!e[l]&&0!=$[i][l]&&r[i]!=Number.MAX_VALUE&&r[i]+$[i][l]<r[l]&&(r[l]=r[i]+$[i][l])}printSolution(r)}let graph=[[0,4,0,0,0,0,0,8,0],[4,0,8,0,0,0,0,11,0],[0,8,0,7,0,4,0,0,2],[0,0,7,0,9,14,0,0,0],[0,0,0,9,0,10,0,0,0],[0,0,4,14,10,0,2,0,0],[0,0,0,0,0,2,0,1,6],[8,11,0,0,0,0,1,0,7],[0,0,2,0,0,0,6,7,0]];dijkstra(graph,0);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
stefanvonderkrone profile image
stefanvonderkrone

the NodeList returned by querySelectorAll has a forEach method, so there is no need to convert it to an array. (developer.mozilla.org/en-US/docs/W...)
Regardless, great article. Thx :)

Collapse
 
peboycodes profile image
Paul

You're absolutely right! The NodeList returned by querySelectorAll does have a forEach method, so converting it to an array isn’t always necessary. Thanks for sharing that!

And thank you for the kind words—glad you found the article helpful! 😊

Collapse
 
chris_sd_b9194652dbd4a1e profile image
Chris S-D

I think one liners can be useful if they are easily read and understood.

I tend to have two-three liners more often than not.

You do need to keep in mind what the potential consequences are, as well as the cost.

In general, if you can write a short function that is easy to follow and be understand that also, by its name, is more clearly understood as to what it does, then generally, yeah, go for it.

You may find that you need better security or performance in some areas and this may require adding or rewriting functions so that they better meet the needs, but usually readability is my number one priority.

I noticed in some of your examples, the "one line" is extremely long.

If the line is over 80-100 characters long, particularly if there are multiple branches on a single line, then I usually prefer not to make that into a single line function.

As others have mentioned, just because you can make something shorter, that doesn't necessarily mean you should. However, if you can make the code shorter and simultaneously easier to read, follow and understand then that's the way to go.

Collapse
 
ktbsomen profile image
somen das

😂you just write the functions in one line without the spaces in the denounce function

Collapse
 
peboycodes profile image
Paul

Haha, you're right! Sometimes it’s easy to overlook those extra spaces. Thanks for pointing that out! In practice, readability still matters, even for simple one-liners. Balancing conciseness with clarity is always key. 😄

Collapse
 
niel_aras_1fec0ebbf7d62ab profile image
niel aras

It’s great to see how powerful and concise JavaScript can be with the right techniques. By using modern features, we can dramatically improve the readability and efficiency of our code. Whether you’re cleaning up an existing project or starting a new one, these one-liners will help you tackle common problems in a sleek, maintainable way. If you're looking for a place to explore more practical examples, you might find helpful resources like Arrestss-va, which can provide further insights on optimizing your web development practices.

Collapse
 
plutonium239 profile image
plutonium239

Less # of characters != Better source code

If that were true, we would be learning how to write minified code.

Collapse
 
brian_ernesto profile image
Brian Ernesto

Succinct code is beautiful and useful.

But, “short” code is useful to me “only” when it allows me to load more into my mind at once without sacrifices.

  1. Does the reduction in verbosity allow me to see more related code for a better understanding, yet avoid obfuscating its operation?
  2. Does the reduction avoid sacrificing performance and functionality for this brevity?
  3. Can others, or future me, quickly understand it?

If so, it’s not a choice, but an obligation.

If it doesn’t meet the prior criteria, you shouldn’t be doing it.

Collapse
 
peboycodes profile image
Paul

Well said! Succinct code is powerful when it enhances understanding, performance, and maintainability—without sacrificing clarity or functionality. It should enable others (or future versions of ourselves) to easily understand and extend the code.

When brevity serves those purposes, it becomes more than just a choice; it becomes an obligation to write clean, efficient, and readable code. Thanks for sharing this thoughtful perspective!

Collapse
 
deathcrafter profile image
Shaktijeet Sahoo

Ohh to be back in time.