What are the best practices to be followed while using JavaScript?

HTMLJavascriptProgramming Scripts

The following are the best practices to be followed while using JavaScript −

End switch with default

Yes, it is a good practice to end switch with defaults. Always end it with defaults.

Create and use Varibles

In JavaScript, only create variables, which you will use and save values. Use the following and avoid unnecessary lines of code and variable declaration −


Avoid the usage of with

The with keyword do not have a good impact on JavaScript speed. Avoid using it in your code.

Faster Looping 

While using a loop, keep the assignment outside the loop. This would tun the loop faster −

var i;
// assignment outside the loop
var j = arr.length;

for (i = 0; i < j; i++) {
   // code

Avoid using Eval()

The usage of eval() function in JavaScript can lead to security issues.

Declaration always on top

It is a good practice to place all the JavaScript declarations at the top −

  • Gives a single place to check for all the variables.
  • Helps in avoiding global variables
  • Re-declarations are avoided.
  • The code is easy to read for others as well.
Published on 26-Feb-2018 09:38:26