Javascript is an awesome programming language, however, writing clean javascript code can be a challenge, even for seasoned programmers.
What does clean javascript code look like? It should be:
- Easy to read
- Easy to debug
- Efficient and high performing
Here are the top tools and tricks you can use take your Javascript code quality to the next level:
1. Use a try catch on all api requests & JSON methods
Numerous things can go wrong when making api requests to fetch data, so taking care of these scenarios are a must. When handling JSON don’t automatically trust what is being given, try to make your code more robust by handling possible inconsistencies.
2. Use a linter (ESLint)
A linter is a static code analysis tool that will check for programmatic and stylistic errors based on a predefined set of rules and configuration. In short it will improve your Javascript/Typescript and help keep it more consistent.
3. Track Javascript issues in your editor
A major component of keeping your Javascript codebase clean is making it easy to track and see issues in the code itself. Tracking codebase issues in the editor allows engineers to:
- Get full visibility on larger issues like tech debt
- See context for each codebase issue
- Reduce context switching
- Solve tech debt continuously
You can use various tools to track your technical debt but the quickest and easiest way to get started is to use the free Stepsize extensions for VSCode and JetBrains that integrate with Jira, Linear, Asana and other project management tools.
4. Utilise template strings
Template strings will allow you to inject values into the string while preserving the format and the code is much more reader friendly than doing string arithmetic.
5. Utilise regex when needing to search strings
Although regex can seem esoteric from the outside, it is such a powerful string parsing tool and allows you to construct complex patterns to account for a variety of difficult string matching scenarios.
6. Utilise optional chainings
Stop having long logical conjunctions and simplify your code with optional chaining.
7. Avoid nesting
Nesting is a sure fire way to increase the complexity of your code and make it much harder to read and comprehend. Consider refactoring if it’s more than two levels deep, by having root level return conditions, shorter blocks and abstracting nested logic to its own functions.
8. Comment all atypical code, but don’t let it replace code readability
There will be times when you have to handle uncommon scenarios where there aren’t established conventions. Commenting this code to help explain what it does and the context that is being considered will greatly help other programmers as well as be a reminder to yourself when you return to the code in the future. But this should not be used as a crutch for not being thoughtful around writing readable code in the first place!
Latest comments (35)
Nice Article
*** 5. Utilize regex when needing to search strings
I'd suggest actually using a 3rd-party or open-source library for any form-based user
input validation with regular expressions: validation rules for shipping (even residential on occasion), email, financial instruments (credit cards, etc) do change though typically not often. However, it has been a problem on the web for a long time (ex. old forms would often validate emails with only a subset of today's available TLDs and fail for legitimate user input). A library for this type of validation, if maintained by a 3rd-party, typically can also be configured to auto-update during your CI deployments and other assorted internal hooks. The point is to lessen the risk of new valid user input not validating due to something esoteric, a change, or update. In addition, you should try to setup form submission and validation using a central service in whatever framework you coding with so that you can maintain all your user input validation in a central way (though with bigger corps its often not possible to get rid of all the separate user-input UI but you can try to centralize the submissions and validation). Anyway, hope this was helpful and I've been a big proponent of Regex's for many years -- glad to see their support in the HTML5 input fields with the 'pattern' attribute (for HTML user-input validation without code). But, one last note: regex's can be difficult to maintain for newer coder and those who maybe come from a design background originally. So, take the author's advice in his last tip and always rely on making the best choice for your code with readability and comments. Regex's were pretty simple too when I started with them but with the latest spec updates to ECMAScript, the advanced regex lexicon is now available as well (just like in PERL, TCL, etc but the grammar can get very confusing for those unfamiliar). With great power comes great responsibility... even in code, and especially (apparently) with regular expressions ;)
Also, I diverged from the author's explicit statement about searching strings. I love regex and we all use them with grep but not sure exactly what context he meant in this case. If you're searching in strings though, it would be much clearer in your code to use substring, substr, indexOf, charAt, slice, splice, or match (all methods of the String object). If you're looking for clean code, you may want to opt for the highly optimized algorithms our modern browers' JS runtimes use for built-in object methods versus a regular expression (if it's a complex search, regex is the best but use one of the String methods for clearer code).
For sure, the best advices I've heard so far.
Nice!
I use 7 out of 8 items. The only one I don't use is eslint. It is not used in the company I work for. I could not convince the people working in the company to use eslint, but I use eslint in my personal projects.
Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍
I always forget about optional chaining! Thanks for the reminder and the great article.
That's awesome.
Thanks for sharing :)
My 2¢ - Code should be readable, regex isn't (at least by a lot of developers who will read the code someday).
Developers should be able to read regex (at least to a certain degree) and they should be aware of ReDoS. But I agree that there is a point where regex are becoming too complex and unreadable and reduce maintainabililty.
how would you validate email and phone numbers WITHOUT regex?
You don't validate email addresses with regular expressions. If you try, there's a 99.9% chance you will get it wrong.
Tslint has been deprecated..
Thanks for sharing these tips in detailed.
TSLint is depricated. Use ESLint for botth Javascript and Typescript. palantir.github.io/tslint/
"Use a try catch on all api requests & JSON methods" I'de argue you should have abstract methods which deal with this sort of thing as middleware. I don't like seeing try catches in all the controller's, rather abstract that away so developers writing controllers it's all been accounted for them already. I consider these sort of this strategic code of your own framework and should be done uniformly and abstractly.
If this is code that you are maintaining, you should catch and log errors where they happen for good telemetry. On client side, there should be a service for logging back to the server to capture as many of those as possible. Even if it is flaky as the service could be down, that could be mitigated a bit with a logging cache on the client side.
Waiting until you are outside of the controller could lead to not having the internal variables to log for debugging. Yes, this might not be the cleanest code, but I would prefer to know the exact cause instead of a vague idea of what is failing.
Don't Error objects bundle up their stack traces from the throw's point of origin anyways?
Absolutely, errors should not be used for control flow which is promoted a lot in JS. Anything unexpected should bubble unless you can deal with it at the call site. A Data Adapter pattern is a much better choice for remote data validation/parsing - which can also remove the need for optional chaining which spreads like a virus and shouldn't be considered a good default.
youtu.be/ITogH7lJTyE