Web Technologies

JavaScript – Best Practices

This is the complete list, yet some of the best practices we follow when we code. Keep reading

Declarations
Declaration should ends with semicolons properly
Variable/function declarations should always with var keyword

var myfunction = function() {};


Linting

The best tool for linting your JavaScript code is JSHint.(https://jshint.com/)


Don’t Use Short-Hand

The curly braces should be omitted is with one-liners.
if(1 + 1 === 2) return 'correct'; // one-line
if(1 + 1 === 2) {x=true; anotherFunctionCall();};


Use
=== Instead of ==
Working with == and !=, leads into issues while using different types, so better way is to use === and !==


Avoid long argument list

Use a single object as parameter , it helps in handling optional parameters.

function getRegisteredUsers ({ fields, include, fromDate, toDate }) { // Implementation}

getRegisteredUsers({
fields: ['name','email'],
include: ['favorites'],
fromDate: '2019-05-05',
toDate: '2019-05-10'
});


Optimize loops

Loops may slow down and the most common mistake is to read the length attribute of an array at every iteration.


Avoid nesting

Nesting is hard to follow on complex logic, little bit confusing too.


Place Scripts at the Bottom of web Page

Always place the scripts at end bottom of the page, which helps to load the page as quick as possible.


Use {} Instead of New Object()

There are several ways available to create a object. Best way I suggest is to use {} instead of new Object();
var a = {}; // Correct
var a = new Object(); // wrong


Use [] Instead of New Array()

Best way to declare a array is to use [] instead of new Array();
var teams = ['a','b','c'];


Comment the Code

Comment or describe(shortly) the code for better understanding. It may helps while we visit the code later.

Author


Avatar