JavaScript Programming Styles: Best Practices

by Janeth Kent Date: 28-10-2021 javascript


When programming with JavaScript there are certain conventions that you should apply, especially when working in a team environment. In fact, it is common to have meetings to discuss standards to follow. The reason is that code is much more readable when certain standards are followed. We have already seen in another article some of the worst JavaScript practices, explaining certain things to avoid. But when we talk about good practices we are not only referring to those that have a better performance, but also to the way you program. In addition to making sure that the code is syntactically correct, you should also be concerned about styles; that is, things like where you place the opening and closing braces or the spaces you use as indentation or indentation in the code.

 

What are programming styles

 

Programming styles are nothing more than an agreement you make with your team and yourself about the styles and standards you will follow in a project. The goal of following a style is to achieve a consistent result, with code that is easy to understand and maintain. Even if you are working alone on a personal project you should follow certain standards. You may not see why during its initial release, but you will when you modify the code in a few months or when another programmer starts working on the project as well.

 

The importance of styles

 

Programming is something similar to craftsmanship, where factors such as creativity, perseverance and expertise come into play. For example, you can paint a wall and leave it smooth, with everything perfectly clean around you, or you can paint the wall with irregularities or hand marks, fill the floor with paint, and leave it all over. The same thing happens with programming, becoming even more important, because when many programmers modify the same code over and over again, if each one applies his own rules, the result may look more like the second case.

It is very common that some inexperienced programmers do not care about this, since they have not yet been able to understand its importance. I was also one of them and absolutely all programmers have been. Besides, it is in this kind of little things where the team leaders will perceive your experience.

 

Sets of style standards

 

There are different sets of standards that you could follow. Each company has its own, and that is what styles are all about, following the same ones within the framework of a company or project, without there being a set that is better or worse. Here are the two most famous sets of styles:

In my case, the styles I follow are very similar to AirBnb's, as they are the ones I've gotten used to in the companies I've worked for. If you prefer another set use it, but don't change it until you finish the project.

You also have the option of using tools like ESLint or Prettier, which somehow force you to use certain rules.

 

Method, function and variable notation

 

There are different types of notations that you could follow when defining the names of functions and variables. The most famous are the following:

Camel Case: This style combines the words of the names you define, setting the first letter of each word to be capitalized except for the first word, with the rest of the letters being lowercase. If you wanted to define an account management function using Camel Case, its name would be accountManagement.

Pascal Case: This style combines the words of the names you define, establishing that the first letter of each word is in upper case, including the first word, the rest of the letters being in lower case. If you wanted to define an account management function using Pascal Case its name would be GestionDeCuentas.

Snake Case: This style combines the words of the names you define, setting all letters to lower case and all words to be separated by an underscore. If you wanted to define an account management function using Snake Case its name would be account_management.

Kebab Case: This style combines the words of the names you define, setting all letters to lower case and all words to be separated by a hyphen. If you wanted to define an account management function using Snake Case its name would be account-management.

There is no better method, although the truth is that in JavaScript the Kebab Case would be practically discarded. The usual is to use Pascal Case for class names and Pascal Case for almost everything else, although there are many developers who prefer to define variable names with Snake Case. If you want more examples, see the guide with the different types of notation for names.

 

Rules to use: Yours

 

That's the way it is and will be as long as you are consistent. Here are mine, which although they are very similar to AirBnb's, they don't coincide 100%:

Semicolons: Many developers choose not to put them at the end of each line, although in my case I use them religiously at the end of each line to avoid possible problems that could occur in some cases.

Spaces: I always prefer to use more spaces than less. I usually use them whenever I close a parenthesis unless it is the end of a line and also before and after the symbols of arithmetic operations such as +, -, / or *, checks or conditions.

Blank lines: I use a line break to separate blocks of code that deal with different logical operations. This way I think it is easier to read the code.

Indenting: I use 4 spaces instead of pressing the tab key. It is also common to use two spaces.

Line length: The length of my lines does not exceed 120 characters. Many developers opt for 80 characters, but I find it too short. I have a bad habit of using lines that are too long.

Comments:I usually use comment blocks to document the code, and in case of commenting something, I write the comment in the line above the one I want to comment instead of writing it at the end of the line. In the same way, I only write the comments that are necessary. That is, I don't use comments when the code blocks that follow the JSDoc standard are sufficient or when the variable names make it very easy to understand what I want to do.

Variable declarations: I never declare variables with var. I use const when a value or reference is not going to change, and let when I want to declare a variable. I always declare constants first and then variables, being both at the beginning of the document in the case of global variables, or at the beginning of functions, in the case of local variables. This way we avoid the unwanted effects of JavaScript hoisting.

Function structure: I use arrow functions whenever possible because of the treatment of this. Sometimes, as in the case of constructors, it is not. Whenever I can, I define functions like this:

 
const miFuncion = (a, b) => a * b;
 

Variable names: I always use Camel Case, although until not too long ago I used Snake Case. This is an example of camelCase

Class names: In this case I use Pascal Case, both in the class name and in the name of the file that includes it. This is an example of PascalCase.

Single or double quotes: Whenever possible I use single quotes instead of double quotes. I usually reserve double quotes for HTML attribute tags, so that if I have to insert JavaScript inside them, I can do it with double quotes. I also apply this criterion with other programming languages such as PHP.

Template Literals: These are expressions that use inverted quotation marks ` to define strings. Whenever I have to insert variables in text strings, I use these quotes, inserting the variable in the middle. In the following tutorial you can find more information about template literals. Example: `Here I am inserting a ${variable}` .

Function and method names: As in the case of variables, I use Camel Case for both functions and methods of classes. Example: CamelCase.

If statements: In this case I usually use two varieties, since I can place the statements in one or several lines depending on how long they are:

 
// If normal  
if (condition) {    
  // code 
}
    
// If con un else  
if (condition) {    
  // código  
} else {    
  // code  
} 
   
// If with several else  
if (condition) {    
   // code  
} else if (condition) 
{    
  // code 
} else {    
// code
 }
 

In the case of very short statements, I use a single line. This is something quite criticized by some developers but I find it very readable as long as the statements are very short, like when you make assignments to a variable. In any other case I use several lines:

 
// If normal
if (statement) variable = true; 
   
// If with one else  
if (statement) variable = true;  
else variable = false;
 

Switch statements: In this case I always define a default condition and also use several lines:

 
switch (expression) {    
case expression:      
// code    
default:      
// code  
}
 

For loops: I always use several lines. In this case I always initialize the element defining the loop iterations in its own definition. I consider this better than inserting it in the condition. I separate the different elements of the loop definition by a ;:

 
for (initialization; condition; update) {    
// code 
}
 

While loops: I always use several lines:

 
while (condition) {
  // code
  }
 

Do while loops: I don't usually use this loop too much. In several lines:

 
do {
  // code
  } while (condicion);
 

Try/catch/finally statements: This is how I define them:

 
// try catch
  try {
  // code
  } catch (error) {
  // code
  }

// try catch finally
  try {
  // code
  } catch (error) {
  // code
  } finally {
  // code
  }

Whatever style you choose, remember that the important thing is to be consistent and maintain it throughout your project.
 
by Janeth Kent Date: 28-10-2021 javascript hits : 10496  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

Node.js and npm: introductory tutorial

In this tutorial we will see how to install and use both Node.js and the npm package manager. In addition, we will also create a small sample application. If you…

How to connect to MySQL with Node.js

Let's see how you can connect to a MySQL database using Node.js, the popular JavaScript runtime environment. Before we start, it is important to note that you must have Node.js installed…

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

How to get DOM elements with JavaScript

When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you…

How to reverse an array in JavaScript

In this tutorial we are going to see how you can change the order of the elements of an array so that they are inverted. You could use a loop…

How synchronize the scroll of two divs with JavaScript

In case you have two divs of different sizes you may sometimes want to scroll both at the same time but at different speeds depending on their size. For example,…

How to use the codePointAt method in JavaScript

The JavaScript codePointAt method has more or less the same function as the charCodeAt method, used to get the 16-bit Unicode representation of the character at a certain position in…

How to check if a value is a number in JavaScript

In this short tutorial we are going to look at the various methods that exist to find out if a value is a number in JavaScript.   1. Using the isNaN() function   One…

How to use the charCodeAt method in JavaScript

The charCodeAt method is accepted by strings in JavaScript, returning the 16-bit Unicode code of the character at the position we pass as a parameter to the method. The charCodeAt method…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration