For the past four years, I have been working on a Cordova app that runs on JavaScript. The codebase has grown to the point where working on it often feels like wandering through streets and alleys of a large city. And looking at some of the earlier modules feels like sauntering into old buildings I originally constructed years ago.
While my JS coding has evolved over this time, I often run into code in the app that feels inefficient and outdated - and it bothers me to the point where I usually feel compelled to eventually refactor it so that it is more compact, readable, and understandable.
Here are 7 time-tested tricks I use to rewrite my JavaScript code from those early days, published this month in Better Programming. I hope you find them useful. Enjoy!
Top comments (8)
Love that quote. So darn relatable...
So glad!
#4: you may want to consider using the nullish coalescing operator
??
(use||
consciously if you want to catch all falsy types).#6:
for...of
is not neccessarily more readable thanforEach
, especially if you use arrow functions.#7: you can use
Object.assign
on DOM elements, e.g.About "for...of": I find myself using it often with async/await. Foreach() does not work well with asynchronous code. I think this was the author's point.
For more background see this: stackoverflow.com/questions/375766...
It depends. If you want to wait on a list of promises returned by an array of functions, better use
await Promise.all(fns.map(fn => fn())
, as it will allow you to run them parallel.Great points, Alex. There is no one right way to make code more readable and your tips are very much appreciated. I never like to be dogmatic about recommendations - these are just things that have worked for me.
You can use Object.assign with DOM objects, too.
Great point about Object.assign(), Pacharapol! I look forward to trying that soon. Again, no one right way to go about it and I very much appreciate your input. What a terrific community of developers we have in this thread.