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...
For further actions, you may consider blocking this person and/or reporting abuse
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
structuredClonefunctionYou'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
.flatare 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! ๐
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.
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!
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
JSONtechnique is not only slow because of the double-pass processing, it is also fraught with hazards. Check the exceptions that can be thrown: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.
the NodeList returned by
querySelectorAllhas aforEachmethod, so there is no need to convert it to an array. (developer.mozilla.org/en-US/docs/W...)Regardless, great article. Thx :)
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! ๐
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.
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.
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.
If so, itโs not a choice, but an obligation.
If it doesnโt meet the prior criteria, you shouldnโt be doing it.
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!
Less # of characters != Better source code
If that were true, we would be learning how to write minified code.
๐you just write the functions in one line without the spaces in the denounce function
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. ๐
Ohh to be back in time.