10 Must-Know Tips for Writing Clean Code With JavaScript

10 Must-Know Tips for Writing Clean Code With JavaScript

JavaScript is a powerful and versatile programming language that is widely used for building web applications, but it can be challenging to write clean, maintainable code. Here are 10 tips to help you write clean code with JavaScript, along with code examples to illustrate each point:

  1. Use meaningful variable and function names: Using descriptive and meaningful names for variables and functions will make it easier for other developers (or future you) to understand the purpose of your code. For example, instead of using a variable name like "x," you could use a name like "userName" or "customerAddress".
    // bad
    let x = 1;
    
    // good
    let userId = 1;
    
  2. Keep functions short and focused: Functions should have a single, clear purpose. If a function becomes too long or complex, consider breaking it down into smaller, more focused functions.
    // bad
    function calculateTotalPrice(items) {
      let total = 0;
      for (let i = 0; i < items.length; i++) {
        total += items[i].price;
      }
      if (total > 100) {
        total = total * 0.9;
      }
      return total;
    }
    
    // good
    function calculateTotalPrice(items) {
      return items.reduce((total, item) => total + item.price, 0);
    }
    
    function applyDiscount(total) {
      return total > 100 ? total * 0.9 : total;
    }
    
  3. Use comments to explain complex or non-obvious code: Comments can help to explain the purpose and behavior of your code, making it easier for other developers to understand and work with.
    // This function takes a string and returns the first letter
    function firstLetter(str) {
        // Get the first letter of the string
        return str.charAt(0);
    }
    
  4. Avoid using global variables: Global variables can make your code harder to understand and maintain, as they can be accessed and modified from anywhere in your code. Use function scope or modules instead.
    // bad
    let name = "John";
    
    function sayHello() {
      console.log(`Hello, ${name}!`);
    }
    
    // good
    function sayHello(name) {
      console.log(`Hello, ${name}!`);
    }
    
  5. Use consistent indentation and spacing: Consistent indentation and spacing can make your code more readable and easier to understand.
    // bad
    function sayHello(name){console.log(`Hello, ${name}!`);}
    
    // good
    function sayHello(name) {
      console.log(`Hello, ${name}!`);
    }
    
  6. Use arrow functions and template literals: Arrow functions and template literals can help you write more concise and readable code.
    // bad
    let names = ["John", "Jane"];
    let greetings = names.map(function (name) {
      return "Hello, " + name + "!";
    });
    
    // good
    let names = ["John", "Jane"];
    let greetings = names.map((name) => `Hello, ${name}!`);
    
  7. Avoid using null and undefined: Instead of using null and undefined, use default function parameters, destructuring, and the Optional chaining operator to handle missing values.
    // Using default function parameters
    function getUser(id, name = 'unknown') {
      console.log(`User ${id} is named ${name}.`);
    }
    getUser(1); // prints "User 1 is named unknown."
    
    // Using destructuring
    const user = { id: 1, name: 'John' };
    const { id, name = 'unknown' } = user;
    console.log(`User ${id} is named ${name}.`); // prints "User 1 is named John."
    
    // Using the Optional chaining operator
    const user = { id: 1 };
    console.log(`User ${user.id} is named ${user.name?.toUpperCase()}.`); // prints "User 1 is named undefined."
    

    In this example, the getUser function uses a default parameter for the name, so if no name is provided, it defaults to 'unknown'. The destructuring assignment uses a default value for the name, so if the user object doesn't have a name property, it defaults to 'unknown'. The optional chaining operator ?. is used to access the toUpperCase() method on the name property, if the name property is not present, the toUpperCase() will not be called and it returns undefined instead of throwing an error.

    By using these techniques, you can handle missing values in a clean and readable way, without having to check for null or undefined values explicitly.

    It's worth mentioning that, this is just one way to handle missing values in JavaScript, and other ways include using the || operator, or the Object.get() method.

  8. Use error handling: Proper error handling can help you to avoid bugs and crashes in your code.
    try {
      // Code that may throw an error
      const value = JSON.parse('invalid JSON');
    } catch (error) {
      // Code that will be executed when an error is thrown
      console.error(error);
    } finally {
      // Code that will be executed regardless of whether an error was thrown
      console.log('This will always run.');
    }
    

    In this example, the try block contains the code that may throw an error, in this case it's trying to parse an invalid JSON. If an error is thrown, the code in the catch block will be executed, in this case it's logging the error to the console. The finally block contains the code that will be executed regardless of whether an error was thrown, in this case it's logging a message to the console.

    This is a basic example of how you can use the try-catch statement to handle errors in your code. You can also use throw statement to throw your own error and try-catch-finally to handle it.

    It's important to note that in javascript, try-catch statement only catch the synchronous errors and throwed errors with the throw statement, asynchronous errors (like network errors, timeouts, and other) are handled with other method like promise.catch(), async-await or EventEmitter.

    By using proper error handling, you can prevent bugs and crashes in your code, and make it more robust and reliable. Additionally, proper error handling allows you to handle unexpected situations in a controlled way, which can provide a better user experience.

  9. Use linters: Use a linter like ESLint to check your code for errors, inconsistencies, and potential bugs. See how you can use ESLint to check your JavaScript code
  10. Test your code: Writing tests for your code can help you to catch bugs and ensure that your code works as expected.

By following these tips, you can write clean and maintainable code with JavaScript that is easy to understand, debug, and modify. Remember that writing clean code is an ongoing process, and requires practice and discipline to develop the skills.

1 Comments

  1. 11: Use linespacing to seperate chucks of code. This also applies to text/documentation, for instance to make sure tip #10 is not overlooked so easily :)

    ReplyDelete
Previous Post Next Post