Coding Standards - JavaScript Best Practices - Part 3

JavaScript JQuery
These articles will give you details on best practices for writing JavaScript code.



This is part 3 for JavaScript standards. Previous 20 coding standards are present in part 1 and part 2 of the article.

21. Use Parameter Defaults

If a function is called with a missing argument, the value of the missing argument is set to undefined. Undefined values can break your code. It is a good habit to assign default values to arguments.



function myFunction(x, y) {
    if (y === undefined) {
        y = 0;
    }
}



22. Modularize your code, one function per task. Do not combine multiple tasks in one function. Avoid heavy nesting of code.


23. End Your Switches with Defaults.


24. Avoid Using eval().

The eval() function is used to run text as code. In almost all cases, it should not be necessary to use it. Because it allows arbitrary code to be run, it also represents a security problem.


25. Reduce Activities in Loop.

Loops are often used in programming. Each statement in a loop, including the for statement, is executed for each iteration of the loop. Search for statements or assignments that can be placed outside the loop.


26. Avoid Unnecessary Variables

Bad


var fullName = firstName + " " + lastName;
document.getElementById("demo").innerHTML = fullName;

Good


document.getElementById("demo").innerHTML = firstName + " " + lastName



27. Use {} Instead of New Object()


28. Use [] Instead of New Array()


29. Always, Always Use Semicolons


30. Conditions can be shortened using “ternary notation”.

For example, the following construct defines a variable as 1 or -1, depending on the value of another variable:


var direction;
if(x > 100){
 direction = 1;
} else {
 direction = -1;
}



This can be shortened to a single line:


var direction = (x > 100) ? 1 : -1

Written by Piece User : pooja@oneact.jp