DEV Community

Cover image for 8 must-know tips for writing clean code with Javascript

8 must-know tips for writing clean code with Javascript

Alex Omeyer on October 27, 2022

Javascript is an awesome programming language, however, writing clean javascript code can be a challenge, even for seasoned programmers. What does...
Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

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.

Anywhere between 4 to 5 levels of nesting is okay; and forcibly getting rid of it often risks turning the code into spaghetti where a single unit of business logic gets spread out over multiple co-dependent functions.

A better approach, imo, is to treat each level of nesting as a point where you should ask "Is this inner block its own unit of logic?" if yes, extract it, if not, leave it.

Collapse
 
saniewski profile image
Paweł Saniewski

Projects I've worked on had Sonar Quality Gates configured. It's a great way to keep high quality code and teach developers clean code practices at the same time.
I remembered because there were a lot of issues concerning deep nesting of if-else statements 😂

Collapse
 
erfan1995 profile image
aliriza erfan

Sonar Quality Gates, Is it extension to be installed to VS Code or any other editor?

Thread Thread
 
saniewski profile image
Paweł Saniewski

SonarQube is an application that you can either run locally or on a remote server and integrate to your CI/CD pipeline. It's connected to your git repository and every time a commit is pushed to a branch, SonarQube runs the code analysis and provides reports on the code quality.
Quality Gate is just a name of the part of the pipeline which checks if the code quality check passed in order for the pipeline to continue the deployment.
You can read more in the docs on the official website of SonarQube! :)

Collapse
 
srjsdev profile image
Steven Olsen
Collapse
 
dopamaxe profile image
Tyler Arrigoni

I think about how I will/would test each portion of my code which drives out the levels naturally. This usually means more and smaller testable well named functions and then a larger testable function that consolidates them and reads cleanly when I return to it in the future.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

As I said, about 4 to 5 levels of indentation is usually the limit; beyond that, you're almost always doing something unreasonable.

But medium sized functions can be tested just as easily as smaller functions. In fact, you should do this anyway so you're not really saving any work by splitting them into smaller subdivisions and testing those individually.

And there just comes a point where you spend more time writing additional tests than you would just looking at a bigger function and figuring out why it fails the way it does. Tests should not replace debugging tools.

Thread Thread
 
srjsdev profile image
Steven Olsen

But medium sized functions can be tested just as easily as smaller functions

On average/in general: Medium sized funtions have much more cognitive complexity and paths then smaller functions. The smaller the function, the easier it is to test. I recommend 10 lines or less per function as a rule of thumb.

Collapse
 
evolooshion profile image
Indifference engine

"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.

Collapse
 
click2install profile image
click2install • Edited

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.

Collapse
 
jfftck profile image
jfftck

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.

Collapse
 
srjsdev profile image
Steven Olsen

Don't Error objects bundle up their stack traces from the throw's point of origin anyways?

Collapse
 
abregre profile image
Vasilis P
Collapse
 
ravidor profile image
Raanan Avidor

My 2¢ - Code should be readable, regex isn't (at least by a lot of developers who will read the code someday).

Collapse
 
ansghof profile image
Ansgar Hoffmann • Edited

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.

Collapse
 
pavlicko profile image
Just Another Developer

how would you validate email and phone numbers WITHOUT regex?

Collapse
 
ashleyjsheridan profile image
Ashley Sheridan

You don't validate email addresses with regular expressions. If you try, there's a 99.9% chance you will get it wrong.

Collapse
 
jankapunkt profile image
Jan Küster

Note that there are RgeEx that can open your server to DoS if user input is involved. Check your regex accordingly.

Collapse
 
madza profile image
Madza

These are some awesome tips, thanks for sharing 👍✨💯

Collapse
 
musayazlik profile image
Musa Yazlık

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.

Collapse
 
code4joe profile image
Joe Johnson

*** 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 ;)

Collapse
 
code4joe profile image
Joe Johnson

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

// Replace the UK spelling for words ending in "lise" with "lize" for American audiences:
const PARA= $('.comment__body').lastElementChild.innerText;
const reSpace= new RegExp("\\s"); prefer following format:
const myRegex = /lise$/i;

para.split(reSpace).forEach(word => word.replace(myRegex, 'lize');
// the above should work copy/paste in your brower's dev tools.
Enter fullscreen mode Exit fullscreen mode
Collapse
 
gurpreethanjra profile image
Gurpreet Singh Hanjra

TSLint is depricated. Use ESLint for botth Javascript and Typescript. palantir.github.io/tslint/

Collapse
 
qcandag profile image
Bünyamin Can Dağ

Useful!! Thanks.

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍

Collapse
 
rootux profile image
Gal Bracha

Tslint has been deprecated..

Collapse
 
delavalom profile image
Delavalom • Edited

For sure, the best advices I've heard so far.

Collapse
 
guscarpim profile image
Gustavo Scarpim

Nice!

Collapse
 
kishorkunalwork profile image
kishorkunal-work

Thanks for sharing :)

Collapse
 
sohrab09 profile image
Mohammad Sohrab Hossain

That's awesome.

Collapse
 
stephenwhitmore profile image
Stephen Whitmore

I always forget about optional chaining! Thanks for the reminder and the great article.

Collapse
 
siddharthkmehta profile image
Siddharth Kumar Mehta

Thanks for sharing these tips in detailed.

Collapse
 
its_kundan profile image
Kundan Kumar

Nice Article

Collapse
 
snehalkadwe profile image
Snehal Rajeev Moon

Thanks for the great article. :)

Collapse
 
Sloan, the sloth mascot
Comment deleted