Categories
JavaScript Best Practices

JavaScript Best Practices — The Basics

Spread the love

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some best practices we should follow when writing JavaScript code.

Make the Code Understandable

We should make our code understandable.

Variable and function names should be descriptive so we can understand it.

For example, instead of writing:

x y z

We write:

numApples numOranges

We should also write names that makes sense anywhere.

For example, instead of writing:

isOver21()

We write:

isDrinkingAge()

No Global Variables

We shouldn’t use global variables to share code.

The names can easily clash and they may be overwritten by anything.

Therefore, instead of writing:

var current = null;
var labels = {
  foo:'home',
  bar:'articles',
  baz:'contact'
};
function init(){
};
function show(){
   current = 1;
};
function hide(){
   show();
};

We write:

module = function(){
   const current = null;
   const labels = {
     foo:'home',
     bar:'articles',
     baz:'contact'
   };
   const init = function(){
   };
   const  show = function(){
      current = 100;
   };
   const hide = function(){
      show();
   }
   return{ init, show, current }
}();

We put everything in a function.

Stick to a Strict Coding Style

If we stick to a strict style, then we won’t have any problems when it’s worked on by any development.

The code will also work in any environment.

We can use ESLint to make the styles automatically consistent.

Comment as Much as Needed but Not More

We can put comments for things that aren’t described by the code.

Also, we should use /* */ for comments since they work anywhere.

We can comment out code to debug with /* */ :

/*
   var init = function(){
   };
   var show = function(){
      current = 1;
   };
   var hide = function(){
      show();
   }
*/

Avoid Mixing with Other Technologies

If we’re styling, we should use CSS as much as possible.

If we need to style things dynamically, we can add or remove the classes as we wish.

For instance, instead of writing:

const f = document.getElementById('mainform');
const inputs = f.getElementsByTagName('input');
for (let i = 0; i < inputs.length; i++) {
  if (inputs[i].className === 'required' && inputs.value === '') {
    inputs[i].style.borderColor = '#f00';
    inputs[i].style.borderStyle = 'solid';
    inputs[i].style.borderWidth = '1px';
  }
}

We move the styles to the CSS:

.required {
  border: 1px solid #f00
}

And in the JavaScript, we write:

const f = document.getElementById('mainform');
const inputs = f.getElementsByTagName('input');
for (let i = 0; i < inputs.length; i++) {
  if (inputs.value === '') {
    inputs[i].className = 'required';
  }
}

Use Shortcut Notations

We should use shorter notation if it’s abailable.

They don’t impact readabnility and saves typing.

For example, instead of writing:

let food = new Array();
food[0]= 'pork';
food[1]= 'lettuce';
food[2]= 'rice';
food[3]= 'beef';

We write:

let food = [
  'pork',
  'lettuce',
  'rice',
  'beef'
]

It’s short and clear.

Instead of writing:

let x;
if (v){
  x = v;
} else {
  x = 100;
}

We write:

let x = v || 10;

And instead of writing:

let direction;
if(x > 200){
   direction = 1;
} else {
   direction = -1;
}

We write:

let direction = (x > 200) ? 1 : -1;

Modularize

Our code should be modularized.

We can divide them into modules by exporting what other modules will use and importing the needed items.

For example, we can write:

foo.js

export const numApples = 1;

and:

import { numApples } from './foo';

This way, we keep private items and private and expose what we need.

Also, the code is divided into smaller files.

Enhance Progressively

We shouldn’t create lots of JavaScript dependent code.

If we don’t need to manipulate the DOM, then we shouldn’t do it.

Instead, we use CSS for styles as much as we can.

Allow for Configuration and Translation

We should keep shared code in one place so that we can change them easily.

For instance, we can keep them all in a module:

export const classes = {
  current: 'current',
  scrollContainer: 'scroll'
}
export const IDs = {
  maincontainer: 'carousel'
}
export const labels = {
  previous: 'back',
  next: 'next',
  auto: 'play'
}
export const setting = {
  amount: 5,
  skin: 'blue',
  autoplay: false
}
export const init = function() {};
export const scroll = function() {};
export const highlight = function() {};

Conclusion

We should keep code in shared modules and reduce JavaScript operations wherever we can.

Also, we should make code understandable and organized.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *