DEV Community

Cover image for JavaScript/Node Best Practices
Niraj Kumar
Niraj Kumar

Posted on • Updated on

JavaScript/Node Best Practices

My Other lists


I usually follow Airbnb's JavaScript Style Guide, still, I intend to keep this list as reference. Most of these rules will be enforced automatically if you integrate ESLint in your project.

  1. Always use 'use strict' if you are still using es5
  2. Don't use global variables
  3. Always Prefer const over let. Ditch the var
  4. Prefer writing pure functions over stateful functions which mutate data or produce side effects
  5. Learn and use functional composition
  6. Favor functional programming over imperative programming
  7. Use method chaining
  8. Prefer composition over inheritance
  9. Use linters to ensure your code is consistent.
  10. Use Airbnb JavaScript Style Guide for JavaScript (https://github.com/airbnb/javascript)
  11. Avoid client-side console logs in production
  12. Prefer '===' over '=='
  13. Use default arguments instead of short-circuiting or conditionals
  14. Function arguments (2 or fewer ideally)
  15. Encapsulate conditionals in a separate function if possible
  16. Avoid negative conditionals
  17. Learn and practice implementation of SOLID Patterns
  18. Use Promises, not callbacks
  19. Async/Await is even cleaner than Promises, use it more
  20. Use try/catch with async/await
  21. Use Async-Await or promises for async error handling
  22. Don't ignore rejected promises, log it to external logging service
  23. Never use eval
  24. Structure your solution by components
  25. Wrap common utilities as npm packages
  26. Separate Express 'app' and 'server'
  27. Use environment aware, secure and hierarchical config
  28. Distinguish operational vs programmer errors
  29. Use only the built-in Error object
  30. Handle errors centrally, not within a middleware
  31. Exit the process gracefully when an unknown fatal error occurs
  32. Use a mature logger to increase error visibility
  33. Discover errors and downtime using APM products (sentry.io)
  34. Catch unhandled promise rejections
  35. Fail fast, validate arguments using a dedicated library
  36. Use ESLint
  37. Separate your statements properly
  38. Prefer named function over anonymous. Name all functions, including closures and callbacks. Avoid anonymous functions, as it helps in profiling
  39. Require modules by folders, opposed to the files directly
  40. Require modules at the beginning of each file, before and outside of any functions
  41. Detect code issues with a linter
  42. Refactor regularly using static analysis tools
  43. Avoid using the Node.js crypto library for handling passwords, use Bcrypt
  44. Prevent evil RegEx from overloading your single thread execution
  45. Don't block the event loop
  46. Bootstrap using 'node' command, avoid npm start (In container environment)

NOTE: If you want to update this list, please comment, I'll incorporate your changes.

Ref.
https://github.com/goldbergyoni/javascript-testing-best-practices
https://github.com/ryanmcdermott/clean-code-javascript
https://github.com/goldbergyoni/nodebestpractices
https://github.com/RisingStack/node-style-guide
https://github.com/DrkSephy/es6-cheatsheet

Top comments (8)

Collapse
 
steevn profile image
steevn

Prevent evil RegEx from overloading your single thread execution

Can someone give me more information about that? What does that mean exactly?

Collapse
 
nirajkvinit profile image
Niraj Kumar

Here is an explanation:

ReDoS stands for Regular Expression Denial of Service. The ReDoS is an algorithmic complexity attack that produces a denial of service by providing a regular expression that takes a very long time to evaluate. The attack exploits the fact that most regular expression implementations have exponential time worst case complexity, so for larger input strings(the ‘evil regex’) the time taken by a regex engine to find a match increases exponentially.
geeksforgeeks.org/understanding-re...

Here is another:

A flawed Regular Expression pattern can be attacked in a manner where a provided user input for text to match will require an outstanding amount of CPU cycles to process the RegEx execution.
Such an attack will render a Node.js or JavaScript application unresponsive, and thus is referred to as a ReDoS — Regular Expression Denial of Service.
medium.com/@liran.tal/node-js-pitf...

Collapse
 
steevn profile image
steevn

Thank you.
Holy

Thread Thread
 
nirajkvinit profile image
Niraj Kumar

You're welcome :-)

Collapse
 
harrisgeo88 profile image
Harris Geo 👨🏻‍💻

Really like your list! However I have to ask your reasoning behind item no 30.

I have used middlewares designed only for errors in express and serverless node applications and it had a really positive experience. This approach works quite well as it allows your can check if the error is a custom one and then pass the extra params that will help you debug the app. Otherwise it will be a standard error and won’t change your apps behaviour. Thoughts?

Collapse
 
nirajkvinit profile image
Niraj Kumar

Thanks Harris! I believe - the following article sums it well:

It is a wrong practise to handle errors within Express middleware — doing so will not cover errors that are thrown in non-web interfaces.

Without one dedicated object for error handling, greater are the chances of important errors hiding under the radar due to improper handling. The error handler object is responsible for making the error visible, for example by writing to a well-formatted logger, sending events to some monitoring product like Sentry, Rollbar, or Raygun

medium.com/devcbeirut/error-handli...

Collapse
 
gokayokyay profile image
Gökay Okyay

Hey great list! Got a concern for item no 39. In past I’d say ofc do it that way it’s more elegant but when deno came out, it felt better and increased the readability of the code for me. Thanks!

Collapse
 
nirajkvinit profile image
Niraj Kumar

Thanks. Can you please elaborate more with an example?