Categories
JavaScript Best Practices

JavaScript Best Practices — Naming, Style, and Comments

Spread the love

Like any other programming language, JavaScript has its own list of best practices to make programs easier to read and maintain. There are lots of tricky parts to JavaScript, and this means there are certain patterns or features we should avoid. We can follow some best practices to make our JavaScript code easy to read.

In this article, we’ll look at some best practices for styling code to be easy to read. We look at variable and function naming, avoiding global variables, keeping a strict coding style, and commenting code in moderation.

Easy, Short, and Readable Names for Variables, Functions, and Classes

Function names should be short and meaningful. For example, if we want to create a variable to store someone’s birthday, it should have a name that indicates that.

This means that it shouldn’t be a name like b, but it also shouldn’t be something with extraneous words like veryVeryVeryLongBirthdayName. Naming it birthday would be appropriate.

Also, something to avoid is combining value with functionality in names. For example, if we want to write a function to check if someone is over the age of majority, we should name it something like isAdult() instead is isOverEighteen().

This also makes more sense since not every place has age 18 as the age of majority.

We can also consider Hungarian notation for naming variables and functions. The notation combines both the return type and the name into one. Since JavaScript function doesn’t have a fixed return type, we can add a prefix for the type for the function.

For example, if we want to return a boolean with our isAdult() function, we can write bIsAdult() with the b indicating that it’s a boolean.

Keeping names in English is also a good idea since it keeps everything consistent with the rest of the code. All the reserved words like function and new are all in English, so it’s consistent to keep everything else in English.

English is also a more international language so it’s more likely that developers know English than not.

Classes are functions that construct other objects, so their naming should reflect that. For example, if we have a class that construct person objects, then they should be named Person.

Class names should be upper case and indicates what kind of object we’re creating from it.

Avoid Global Variables and Functions

In JavaScript, everything runs in the file runs in the same scope. This is a real problem because things can easily be accidentally modified and referenced unintentionally.

Fortunately, since ES6, JavaScript has several features to deal with this. One is the use of modules. With modules, only the things that we explicitly export are available for other modules to use.

JavaScript strict mode should also be enabled to prevent the accidental declaration of global variables. With strict mode something like x = 1 will cause an error without the keywords var, let, or const before it.

Also let and const are keywords for declaring block-scoped variables and constants respectively, so we can’t accidentally reference it outside a block.

For example, with var if we write the following code:

if (true) {
  var x = 1;
}
console.log(x);

We’ll see 1 logged from the console.log since it’s not block scoped.

On the other hand, if we use let instead of var:

if (true) {
  let x = 1;
}
console.log(x);

Then we get the error ‘Uncaught ReferenceError: x is not defined.’

As we can see, we can’t reference things in places that we don’t expect.

An alternative way would be to wrap the stuff we want to be private in a function.

For example, we can write:

(function() {
  var x = 1;
})();

console.log(x);

We will also get the error ‘Uncaught ReferenceError: x is not defined.’ A function that runs immediately after it’s declared as we have above is called an Immediately Invoked Function Expression or IIFE for short.

If we want to expose something to the outside in the IIFE we have above we can just return what we want as follows:

let foo = (function() {
  var x = 1;
  return {
    bar: 2
  }
})();
console.log(foo.bar);

We returned an object with the bar property and assigned it to foo. Then we should get 2 from the console.log output.

Photo by Mohau Mannathoko on Unsplash

Keep a Strict Coding Style

Every developer in the team will have their own style if they decide how to style the code.

This means that the code will have different styles in different places, making the code hard to read.

Because of that, it’s a good idea to keep the style consistent. We can style our code automatically with programs like ESLint or JSLint, which does static checks on our code to make sure that it sticks to the style that’s set.

There’re also tools like Prettier to format the code in a consistent way through our codebase.

Clean code is easy to read and maintain. It shouldn’t have hacky things that make it hard to read and debug.

Comment When Needed

While lots of code are self-explanatory, some code needs to be clarified. For example, if the code is part of a complex system, then it might need some clarification with comments.

A simple function that’s a few lines long probably don’t need much explanation.

If we write comments, we should use multi-line comments /* */ instead of single-line comments // since they’re more versatile.

One handy trick for comments is to write it with the double slashes before closing the multi-line comments as follows:

/*
  function foo(){
    return 1
  };
// */

This way, we can uncomment the code by putting a slash before the open slash in the first line to uncomment the code:

//*
  function foo(){
    return 1
  };
// */

The code above is uncommented.

Many text editors should also be smart enough to comment and uncomment JavaScript code automatically.

Variable and functions should be named in a way that indicates what they store or do respectively. Classes should start with a capital letter in general and they should be named for the kind of object that they instantiate.

We should avoid global variables since they can be referenced accidentally and cause unintentional modification. We can keep things private inside functions or modules.

To make code easy to read. It’s important to keep a strict coding style so that we don’t get any confusion when reading code.

Finally, we can comment on code in moderation if there’re parts that are harder to understand.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.