JavaScript Best Practices

  • Use nullish coalescing operator ?? instead of "or" operator || to provide default value for variables. Read more
  • Don't block the main thread with long tasks. https://web.dev/optimize-long-tasks/
  • Write pure functions. Pure functions have no side effects since they do not change anything outside their scope. https://www.freecodecamp.org/news/what-is-a-pure-function-in-javascript-acb887375dfe/amp/
  • Use "const" to define variables. This practice helps you to write immutable code.
  • Avoid global variables. If you need a global variable in your app or Website create a global namespace or state object and use that every where.
  • Avoid duplicated code (DRY)
  • Avoid negative conditions
  • Use dataset instead of getAttribute() or setAttribute() to read or write data-attributes. Example:
// HTML
<article data-author-name="John">...</article>

// JavaScript
const article = document.querySelector('#my-article');
const author = article.dataset.authorName;
article.dataset.authorName = 'Tom';