This blog is a comprehensive guide of best practices and preferred ways of implementing JavaScript. These best practices are not absolute rules but recommendations to optimize your JavaSript . I have added sample code along with explanations that will help you understand how one applies the recommendations in actual working code.
1. Don't use Global Variable unless necessary
Avoid using Global Variables unless necessary, because it can be overwritten by other developer’s scripts/code especially in large projects where too many developers are working on same module.
Example
function myMethod() { arrCollection = {} } function othersMethod() { arrCollection = null }
In the above example you will get null value if you alert “arrCollection”, because you have declared a global variable and some other developer has overwritten it by using the same variable name.
2. Don't initialize or Declare Strings, Numbers, or Booleans as Objects
Always treat Numbers, Strings, or Booleans (Data Types) as primitive values. Don’t declare them as objects, it will slow down execution speed and you might get unexpected results.
var x = "employee"; var y = new String("employee"); (x === y) // is false because x is a string and y is an object.
Interaction with the DOM is usually slower than normal JavaScript code because DOM and the JavaScript engine are separate components. However we cannot completely avoid DOM access, but try to minimize its use.
3. Keep Document Object Model Access to a Minimum
Example 1
var hOne= document.createElement("h1"); var t = document.createTextNode("This is Heading"); hOne.appendChild(t); document.body.appendChild(hOne);
Example2 – Better way
var hOne = “<h1>This is heading</h1>” document.getElementById("headingContainer").innerHTML = hOne;
In the above two examples second method of inserting <h1> into DOM is the optimized way because DOM insertion through string is usually faster than creating HTML with DOM methods.
4. Don't use JavaScript reserved words
Don’t use reserved words such as abstract, package, else, false and so on. It will cause you issues when you attempt to run your application. A complete listing of these words can be found at the http://www.w3schools.com/js/js_reserved.asp.
5. Start blocks on the same line
Most developers open curly brace on its own line. This works most of the time but in some cases it might not work as expected.
Example
Wrong Way:
function showAlert() { return { id: 10, name: "myName" } } alert(showAlert())
Correct Way:
function showAlert() { return { id: 10, name: "myName" } } alert(showAlert())
In the above example you would assume that the object would be returned in the alert but instead of object you will get error in the console “SyntaxError: missing ; before statement….” . The reason for this is the browser has inserted a semicolon after the word return, assuming that one is missing. To avoid such circumstances it is considered a best practice to start blocks on the same line to ensure that your code always works as expected.
6. Define default values
If a method or function has some arguments and is called with a missing argument, then you will get the error “undefined variable” and undefined values that can break your code. It is a good practice to assign default values to arguments.
function myFunction(x, y) { if (y === undefined) { y = 0; } }
Or, even simpler:
function myFunction(x, y) { y = y || 0; }
Eval function is called "evil" in Javascript language. Eval takes a String as a argument and JavaScript compiler executes String as JavaScript on run-time.
7. Don’t Use or Avoid eval()
- It is significantly slower than design time code.
- The code written in eval is executed at run-time and that makes it a security risk. When code is executed at run-time, the other programmers can easily excess it and exploit it.
8. Declarations on Top
Always define variables or any declaration on top of functions /script. By doing this you can avoid unwanted global variables and it reduces the possibility of unwanted re-declaration. It also gives a cleaner code and good readability.
9. Always validate your JavaScript
Validate your JavaScript through online tools. Online tools help you to identify common problems and improve your code standard. Below are the lists of good online tools.
10. Use Proper Namespace
Always use proper namespace in your code. Writing all of your functions and variable into the global scope is extremely dangerous and can cause code conflict with other developer's code.
//Your validation method function validation() { alert(“my validation”) } //other developer validation method function validation() { alert(“others validation”) }
In the above example, your function is overwritten by other’s code. To avoid such circumstances use proper namespace.
Better Way:
var MyFunctions = {}; MyFunctions.validation = function(){ alert(“my validation”) }
11. Modularize and Minimize your JavaScript
Normally people start adding everything into one function. However, as you extend the functionality you come to know that you require the same functionality in several functions. This might lead to code redundancy. To prevent that make sure you write smaller and generic helper functions that fulfils one specific task rather than putting all your code in one method.
Also you can combine your all JS files into one file and minimize them.
Note: One 100KB JS file loads faster as compared to ten 5KB JS files.
12. Comment as much as needed but not more
Your comments should be short and explanatory, it should not be a long story. A proper comment helps other developer as well as yourself to understand the code faster (If you are going through your code after several months). There are numerous arguments on whether to use comments at all because good code should explain itself. Avoid using the line comment “//” instead of “/* */” which is much safer to use because it doesn’t cause errors when the line break is removed.
13. Optimize loops
If you don’t use loops properly it will hamper your code performance. The common mistake we do in loops is that we read the length attribute of an array at every iteration.
var employees = ['employee1', 'employee2', 'employee3',..]; for(var i = 0; i < employees.length; i++) { doSomething(employees[i]); }
In the above statement every time the loop runs, JavaScript will read the length of the array. You can avoid that by defining the length value outside the loop and in a different variable:
Better Way:
var employees = ['employee1', 'employee2', 'employee3',..]; var totalEmpNo = employees.length; for(var i = 0; i < totalEmpNo; i++) { doSomeThingWith(names[i]); }
Another point to ensure is that you keep computation-heavy code outside loops such as regular expressions and DOM manipulation and so on.
14. Using HTML Comments in Script is Bad
Older browsers didn't have any support or knowledge of the script tag. Hence a technique was needed to hide the code from older browsers so that they wouldn't show it as text in the page as HTML comments which are used in Script.
<script language="javascript"> <!-- // code here// --> </script>
15. Detect Feature Rather Than Detect Browser
Today almost each and every major browser supports JavaScript and understands <script> tag, so hiding of JavaScript source is no longer necessary.
Sometimes we detect browser versions and take different action or write different code. This is not a good practice and a better approach is to use feature detection rather than browser detection.
Example
var btn = document.getElementById("myBtn"); if (navigator.userAgent.indexOf("MSIE 7") > -1) { btn.attachEvent("onclick", myFunction); // For IE } else { btn.addEventListener("click", myFunction);//For all major browser except IE }
A more effective approach is to detect support for the feature directly, as shown in the following code sample.
var btn = document.getElementById("myBtn"); if (btn.addEventListener) { btn.addEventListener("click", myFunction); } else if (btn.attachEvent) { btn.attachEvent("onclick", myFunction); }
16. Always prefer “Async” Ajax call rather than the “Sync”
There are two types of Ajax calls:
- Async: When you make Async call, other browser request runs simultaneously. It does not wait to finish your Ajax call.
- Sync: Sync mode will wait for the request to return before continuing.
In case the server is busy and response is taking time, the user’s browser will not be allowed anything else and in some cases it will wait to request time out. So if your code needs Sync calls, prefer changing your coding design pattern.
Conclusion
The above points are not the thumb rules, but if you follow them you can avoid many problems. The main trick with JavaScript is to avoid taking the easy path. It is very easy to write sloppy code that does the job but down the line same code creates problems, so always try to optimize your code and find out a better way of writing JavaScript.