Useful JavaScript

The following suggestions will improve your JavaScript making it easier to read and maintain and less obtrusive.

1. Place all of your JavaScript in an external file and unless the script needs to run before the page starts loading attach the script just before the </body> tag at the bottom of the HTML. Only where the script needs to run before the page starts to load should it be attached in the <head>. None of your JavaScript should be jumbled in with the HTML itself. Any JavaScript that would otherwise be included in HTML tags (eg. onclick="") should be replaced by an id or class and that used to attach the JavaScript to the HTML from within the external file instead.

2. Wrap your code in an anonymous self executing function. This keeps the variables in global scope to a minimum and reduces the possibility of clashes between different scripts you add to the same page.

(function() {
// code goes here

You can even do this if you are using a JavaScript library by passing the library to the function.

(function($) {
// code goes here

3. Always specify "use strict"; as the first statement in your function. This provides additional validations that prevent common errors. For example mistyping a variable name and so accidentally creating another global variable becomes impossible. Those commands no longer supported when you apply "use strict"; are ones which would have been removed from JavaScript long ago were it not necessary to still support scripts written for Netscape 2.

4. Declare all the variables your function uses at the top of the function. This is where the declarations take effect so placing them here makes the code match with the way JavaScript works. You can specify them all as a comma separated list in a single var statement.

var i, j, something;

5. Never use == or !=. While these can make your code one character shorter they are less efficient and less accurate than === and !== and they are more error prone to typos if you leave out an =. When comparing variables containing different types you should explicitly convert them to the same type for the comparison where you want that conversion to occur.

6. All form field values are strings. When a number is expected to be entered use Number() to convert the string to a number unless the number uses scientific notation in which case use parseFloat(). Never use parseInt() unless the number is being entered using a number base other than 10 (parseInt supports bases 2 though 36). Where the value is being used with subtraction, multiplication, or division then conversion is not needed. You can also use a unary + instead of Number().

7. Where ever possible use built in methods for processing instead of defining your own code. Where older browsers do not support the method use a polyfill so that new browsers can use the built in method and only the older browsers need to run extra code.

8. Only use "new" with a built in object where there is no alternative. Use [ ] when creating arrays, { } when creating objects and / / when creating regular expressions that do not need to contain variables. Use primitives for booleans, numbers and strings and let JavaScript convert them to the corresponding object when necessary. This only leaves Date and RegExp where the expression contains a variable needing the "new" keyword (plus of course where you are using it with your own objects).

9. Use console.log() and the debugger built into your browser for debugging. There is no longer any reason to use alert(), confirm() or prompt() at all.

10. Internet Explorer 3 is long dead so there's no reason to pass a string as the first parameter to setTimeout() or setInterval() - more modern browsers expect that parameter to be a function.

11. Only use a "load" event where your script requires the entire page to have loaded before it can run. For example a script that substitutes for any image that failed to load needs to wait for the "load" event. A script that is displaying a slideshow does not need to wait.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow