Codiga has joined Datadog!

Read the Blog·

Interested in our Static Analysis?

Sign up
← All posts
Khalid Khan Thursday, June 23, 2022

Top Five Best Practices for JavaScript

Share

AUTHOR

Khalid Khan, Developer Relations Engineer

Khalid is the Developer Relations Engineer at Codiga. He is passionate about Software Engineering. Startups and Developer Advocacy. He is also an MLH Coach and Organizer & Member to numerous Hackathons & Developer communities

See all articles

Programming in JavaScript can be confusing, but it is a critical programming language with tons of frameworks & libraries, so understanding the basics is essential. We have some best practices for using JavaScript.

Why follow JavaScript best practices?

  • Achieve faster page loads
  • Better performance
  • Improve code readability
  • Easy maintenance and debugging
  • Prevent errors and security issues

This blog post will go through some important best practices you should follow while programming with JavaScript.

Before going into the specific best practices, you can get automated code reviews using Codiga. At the end of the blog post, we will also tell you how we can help you code better and faster.

Use short functions

A function is a set of statements that perform a specific operation set. Functions should be short. A typical rule of thumb is that a function should fit on your screen to understand the data flow within the function.

When writing functions, consider a single task that it should accomplish. Do not include multiple operations inside a single function. This makes the code easy to understand and implement. It also enables you to use the “single function’ for another program you might need later. Large functions tend to do many things and make it hard to follow what's going on in the program.

Benefits of using short & Modular functions:

  • Increased efficiency
  • Maintainability
  • Extensibility

Example:

const arrayToCSV = (arr, delimiter = ",") =>
  arr.map((v) => v.map((x) => `"${x}"`).join(delimiter)).join("\n");
arrayToCSV([
  ["a", "b"],
  ["c", "d"],
]); // '"a","b"\n"c","d"'
arrayToCSV(
  [
    ["a", "b"],
    ["c", "d"],
  ],
  ";"
); // '"a";"b"\n"c";"d"'

This snippet converts the elements that don’t have commas or double quotes to strings with comma-separated values. This is a perfect example of a short yet re-usable function. This function can be used and called anytime in the code.

Do not re-declare the same objects

In JavaScript, it is possible to redefine a variable with the same name using var. Although this is not a syntax error, this may lead to confusion about where the variable is declared and initialised. Therefore we should eliminate variables that have multiple declarations in the same scope.

Also, declaring an object or variable as const is one of the best practices. This helps us prevent unwanted changes in types and avoid accidental changes.

It does not mean you cannot declare a variable in the inner scope or do shadowing.

Here is an example of incorrect code:

var item;

function whatToCook(today) {
  if (today === "Monday") {
    item = "samosa";
  } else if (today === "Tuesday") {
    item = "bread";
  } else if (today === "Wednesday") {
    item = "mushroom";
  } else if (today === "Thursday") {
    item = "meat";
  } else if (today === "Friday") {
    item = "paneer";
  } else if (today === "Saturday") {
    item = "Avacado";
  } else if (today === "Sunday") {
    item = "Chicken";
  } else {
    item = undefined;
  }
  return item;
}

result = whatToCook("Wednesday");

console.log(result);

In the above code you can observe that the object is resigned multiple times which have complexed the code. Instead observe the below code. You will find example of correct code:

function whatToCook(today) {
  if (today === "Monday") return "samosa";
  if (today === "Tuesday") return "bread";
  if (today === "Wednesday") return "mushroom";
  if (today === "Thursday") return "meat";
  if (today === "Friday") return "paneer";
  if (today === "Saturday") return "Avacado";
  if (today === "Sunday") return "Chicken";
  else return undefined;
}

const item = whatToCook("Wednesday");

console.log(item);

Write code with less cyclomatic complexity

The cyclomatic complexity indicates the quantitative measure of the number of linearly independent paths through a program's source code.

The cyclomatic complexity of a code section measures the number of linearly independent paths. Simply put, it measures the number of linearly independent paths through a program's source code.

An increase in cyclomatic complexity ultimately affects the space and time complexity, which affects the overall program. We should aim to reduce the number of independent paths in the source code to avoid the issue.

Here is the example of incorrect code with higher cyclomatic complexity:

function a(x) {
  if (true) {
    return x;
  } else if (false) {
    return x + 1;
  } else {
    return 4; // 3rd path
  }
}
function b() {
  foo ||= 1;
  bar &&= 1;
}

Example of correct code:

Here, you can find a very minimal number of linearly independent paths, resulting in less complexity and better performance.

function a(x) {
  if (true) {
    return x;
  } else {
    return 4;
  }
}

function b() {
  foo ||= 1;
}

Comment your code properly

Comments are an excellent way to summarise and understand a code snippet or fragment of code. Comments are a code description, making it easy for other developers to understand your code. These comments will also help you to understand your code & memorize the logic that you have written while writing that code.

Where should comments be placed in your code? beginning of any source file function description

There is a special syntax that should be used while describing your function using comments. These syntax is defined by JSDoc. This can be used to generate property table content using comments.

Incorrect Code:

// Returns x raised to the n-th power.
function pow(base, exponent) {
  var result = 1;
  if (exponent == undefined) exponent = 2;
  for (var i = 1; i <= exponent; i++) {
    result = result * base;
  }
  return result;
}

Correct Code:

/**
 * Returns x raised to the n-th power.
 *
 * @param {number} base The number to raise.
 * @param {number} exponent The power, must be a natural number.
 * @return {number} result = base raised to the exponent-th power.
 */
function pow(base, exponent) {
  var result = 1;
  if (exponent == undefined) exponent = 2;
  for (var i = 1; i <= exponent; i++) {
    result = result * base;
  }
  return result;
}

Labels should not be used

A JavaScript label helps you name a statement, function, or code snippets. Labels that are declared make programs harder to read and understand. This may also increase the page load time and the code's complexity.

You can learn more about labels here. To avoid this issue, we should aim to eliminate labels.

Example:

OUTER_LOOP: for (const customer of customers) {
  if (checkBills(customer.bills)) {
    continue;
  }
  doSomething(customer);
}

In this case, removing OUTER_LOOP: had not been done. Such labels take up space in the code and can confuse readers. Note that: A JavaScript label should not be confused with an HTML <label> element, which is entirely different.

There are tons of other rules & best practices for JavaScript you can follow to provide the best out of your code. Please refer to our documentation to know more.

How can Codiga help you follow Best Practices?

Codiga is a code analysis platform that helps developers produce better code and address technical debt. The platform provides the following features that can help you follow Best Practices.

Code Analysis with historical analysis: analyze each code change and keep analysis history of monitoring trends in your codebase.

Automated Code Reviews: automatically surface code smells, duplicates, or complex functions when sending code for review. Codiga integrates with GitHub, Gitlab, Bitbucket, Jenkins, Travis-CI, and Slack.

Automated Code review reviews a set of source code by a computerized tool. When you install Codiga into your preferred platforms, you are covered. Codiga analyzes the code and surfaces any issue directly from your code hosting platform.

Once the pull/merge request is created over any of our supported platforms, Codiga analyses the code and populates the result directly on the pull request page.

Code Review

Benefits of automated code reviews

Apart from following the best practices in your code, Automated Code Reviews have other benefits.

Ensures consistency in design and implementation: With a software team of larger size, it is tough to provide a particular code design or style as every Developer has their programming style. With Automated Code Reviews, you can define your own rules, ensuring consistency easier.

Better code optimization: Code reviews help junior developers identify areas of improvement and work on their skills. Not all developers t are unaware of specific code optimization techniques that can help them write clean code. These Automated Code Reviews help them identify critical mistakes and errors.

Easy to use: Setting up automated code reviews is very easy. Just a few clicks and you are good to go. All the information you need can be accessed through our Dashboard.

Easy to scale: you can automate the code review process without any issues, even for software teams of a larger size. We review code and provide feedback on every Pull/Merge Request.

Decrease time and human efforts: With this, you can review all the changes made in the code and get reviews on the code quality and best practices. Automated code reviews require minimum human effort. It can be easily integrated with different code collaboration platforms such as Github.

Try Codiga for Free

Wrapping up

This blog post glanced at some best practices you should follow while programming in JavaScript.We discussed how important is to write better code using the best practices. We also went through how code reviews are essential in programming.

Here are some takeaways from the blog post:

  • Use short functions
  • Do not re-declare the same variables
  • Use const rather than var
  • Comment your code often
  • Labels should not be used in your code

We also glanced at how Codiga can help your get automated code reviews and follow the best practices. Note that there are many other best practices & rules you will need to follow. Make sure you have Codiga installed on your computer to avoid any violation.

Learn More

Are you interested in Datadog Static Analysis?

Sign up