CUSTOMISED
Expert-led training for your team
Dismiss
Clean Code JavaScript: 5 Best Practices for Readable Code

11 September 2023

Clean Code JavaScript: 5 Best Practices for Readable Code

Writing clean, readable code is crucial for any JavaScript developer. Clean code promotes maintainability, collaboration, and reduces bugs. Here are 5 best practices for writing clean JavaScript code:

JBI Training can supply the perfect solution for all of your clean coding in Javascript with our Clean Code with JavaScript Course

1. Use Descriptive Variable and Function Names

Using intention-revealing names for variables and functions improves code clarity. Follow these naming conventions:

  • camelCase for variables and functions
  • PascalCase for constructors and classes
  • Avoid single letter variables like a or b
  • Use full words instead of abbreviations

Before:

let a = 10;
let b = 20;

function add(x, y) {
  return x + y;
}

After:

let speedLimit = 10;
let currentSpeed = 20;

function calculateTotal(price, tax) {
  return price + tax; 
}

The improved names clearly convey meaning and intent.

2. Write Small, Focused Functions

Functions should do one thing well. Avoid large, complex functions by splitting them into smaller, reusable ones.

Before:

function processOrder(order) {
  let total = 0;
  // calculate total
  // add shipping 
  // charge credit card
  // send email
  // update database
  // etc  
}

After:

function calculateTotal(order) {
  // calculate total
}

function addShipping(order) {
  // add shipping
}

function chargeCreditCard(order) {
  // charge credit card 
}

This follows the single responsibility principle - each function handles one specific task.

3. Remove Duplicate Code

Duplicate code is hard to maintain. Use abstraction to extract repetitive code into reusable functions, modules, or classes.

Before:

// display user 1  
getUserData(user1);
formatUserData(user1);
render(user1);

// display user 2
getUserData(user2); 
formatUserData(user2);
render(user2);

After:

// reusable display function 
function displayUser(user) {
  getUserData(user);
  formatUserData(user); 
  render(user); 
}

displayUser(user1);
displayUser(user2);

The duplicate code is now consolidated into a single function.

4. Limit Side Effects

Side effects like modifying state or interacting with DOM make functions less predictable. Favor pure functions without side effects where possible.

Impure:

let count = 0;

function increase() {
  count++; // modifies external variable
}

Pure:

function increase(num) {
  return num + 1; // doesn't modify external state   
}

This makes the function reusable without relying on external state.

5. Write Clean Comments

Good comments explain intent, not implementation. Use JSDoc style doc blocks for functions.

/**
 * Returns total price with tax 
 * @param {number} price - Price before tax
 * @param {number} taxRate - Tax rate as percentage
 * @returns {number} Total price after adding tax
*/

function getTotal(price, taxRate) {
  // ...
}

Meaningful comments like this help others understand your code.

By following these best practices, you can write clean JavaScript code that is easy to read, maintain, and build upon. Mastering these core principles is key to becoming a skillful JavaScript developer.

Frequently Asked Questions

What are the benefits of clean code?

Some key benefits of clean code include:

  • Improved readability and maintainability
  • Easier to understand intent and logic
  • More reusable and adaptable
  • Reduced bugs and errors
  • Better for collaboration
  • Easier to modify and update in the future

What makes code "dirty"?

Some examples of dirty code include:

  • Poorly named variables like a, b, temp
  • Giant functions doing many different things
  • Duplicate blocks of code
  • Deeply nested conditionals and loops
  • Too many comments trying to explain complex code
  • Tight coupling between modules/classes
  • Reliance on side effects rather than pure functions

How can I convince my team to care more about clean code?

  • Explain the long term benefits like reduced bugs and easier maintenance
  • Lead by example by writing clean code yourself
  • Do pair programming focused on improving existing code
  • Make it part of your code review process
  • Automate linting/formatting to enforce standards
  • Refactor legacy code bit by bit
  • Show concrete before/after examples of improving code

What tools can I use to write cleaner JavaScript?

Some useful tools include:

  • Linters like ESLint or JSHint
  • Code formatters like Prettier or Beautify
  • Editor plugins for linting/formatting
  • Static type checkers like TypeScript or Flow
  • Unit testing frameworks like Jest, Mocha, Jasmine
  • Automated refactoring tools

What coding standards or style guides help enforce clean code?

Popular style guides include:

  • Airbnb JavaScript Style Guide
  • StandardJS
  • Google JavaScript Style Guide
  • Idiomatic.js
  • Clean Code JavaScript by Ryan McDermott

These provide standards for formatting, naming, testing, and more.

Conclusion

Writing clean code requires diligence and practice, but pays off in the long run. The 5 principles covered here - descriptive naming, small functions, DRY, purity, and comments - are key for any JavaScript developer to master. By keeping your code clean, you can build robust applications that stand the test of time. If you enjoyed this article you might be interested in our next article Mastering Modern JavaScript Styles with ES6+ and Beyond

JBI Training specialises in providing customised training solutions for teams across large enterprise organisations. With dedicated account managers, they work closely with clients to analyse skills gaps and design targeted training programs. Courses can be delivered onsite at the organisation's offices or virtually to remote staff. The training is tailored to the organisation's specific needs and objectives. They can also develop proprietary role-based learning paths aligned to the organisation's roles and competencies.

Hands-on labs, workshops and exercises can be incorporated to reinforce practical skills. JBI's enterprise training services help upskill large numbers of staff efficiently. The customised approach strengthens capabilities across the organisation.

Whether it's programmer training, ITIL adoption or project management  JBI has experience delivering strategic training programs for large corporate clients.

Clean Code with JavaScript - 2 days

This course focuses specifically on writing clean, maintainable code with JavaScript. Through hands-on exercises, you will learn principles like:

  • Writing descriptive, intention-revealing names
  • Breaking code into small, single-purpose functions
  • Eliminating duplicate code through abstraction
  • Limiting side-effects for purity and predictability
  • Adding meaningful comments for documentation

The instructor will demonstrate refactoring messy code into well-structured, legible code. You'll learn JavaScript-specific standards like Airbnb's style guide.

Other courses that may be of interest are 

JavaScript (Advanced)

This advanced JavaScript course builds on basic knowledge to cover advanced topics like OOP, design patterns, ES6/ES7 features, module loaders, build tools, testing and more. Gain skills to develop complex JavaScript applications.

ECMAScript 6 Introduction - 

This introduction to ECMAScript 6/ES6 training covers the major features of the ES6 JavaScript specification. Learn syntax for variables, arrow functions, classes, promise handling, iterators, generators and more.

Node.js - 

This comprehensive Node.js course teaches building web servers and applications with Node. Covers modules, npm, Express, MongoDB/database integration, microservices, testing, deployment and more through hands-on labs.

React - 

This practical React training course teaches building dynamic web UIs with React. Learn key concepts like components, JSX, state management, Hooks API, React Router, testing and more through real-world examples and labs.

 

About the author: Daniel West
Tech Blogger & Researcher for JBI Training

CONTACT
+44 (0)20 8446 7555

[email protected]

SHARE

 

Copyright © 2024 JBI Training. All Rights Reserved.
JB International Training Ltd  -  Company Registration Number: 08458005
Registered Address: Wohl Enterprise Hub, 2B Redbourne Avenue, London, N3 2BS

Modern Slavery Statement & Corporate Policies | Terms & Conditions | Contact Us

POPULAR

Rust training course                                                                          React training course

Threat modelling training course   Python for data analysts training course

Power BI training course                                   Machine Learning training course

Spring Boot Microservices training course              Terraform training course

Kubernetes training course                                                            C++ training course

Power Automate training course                               Clean Code training course