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
 
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
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

For object cloning, just use the built in structuredClone function

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
 
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
 
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
 
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
 
skhmt profile image
Mike πŸˆβ€β¬›

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

Collapse
 
retakenroots profile image
Rene Kootstra • Edited

In the frontend i would debounce with requestAnimationFrame...

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
 
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
 
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
 
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
 
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
 
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
 
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
 
ktbsomen profile image
somen das

πŸ˜‚you just write the functions in one line without the spaces in the denounce function

Collapse
 
deathcrafter profile image
Shaktijeet Sahoo

Ohh to be back in time.