Best practices in Javascript

By | April 13, 2017

Following are the few practices doing in the coding using javascript.

1.Try to Avoid global Variables
In some case we cant able to remove global variable.try to use local variable instead of global variable.your global variable or function defined in the script,if we use the same variable or function in the script again it wil overwrite.

2. Declare variable as local variable

if we define a variable using var keyword, then it will be treated as local variable otherwise it will be global variable.

3.Declare the variables at the Top

variables declaring in a script should be at the top.if we define the variable at the top it will be looks like clean and easy to read.avoid redeclartion of variables.
For example
var one,two,three,four;

4.Value intialization in the begining.

Better to initialize the values at the begining.For example

var price=100; myname=’vasanthan’;

if it is an array =[]; or an object ={};

5. New object usage is not a good practice

declaring number, string, boolean as object it will reduce the speed.

6. use === comparison operator

instead of using == if we use === . it forces the comparison of value and type

7. always use default values to functin parameter

For example function test(z,y);

in this case if you call function as test(1); here value of y is not passing it will treat as undefined in the function so it will break the code,and it throws error. so pass default value for that