Javascript Tips & Tricks
Version your JavaScript
====================
Include js version in the language attribute, e.g. script type=”text/javascript” language=”JavaScript1.4″>
Useful if you want to “hide” code from older browsers .g. if you use try…catch statements (v 1.4)
Variables
=======
Always declare variables with var this is just good consistency, and not doing so CAN cause errors in certain situations (it’s a scope issue).
End of lines
==========
Please, use semicolons. I know javascript doesn’t require them, but use them anyways. It makes code easier to read and EVERY other C-based scripting language requires them
Functions and parameters
======================
Whenever possible, use a function. Likewise, if something is variable, use a parameter. Functions and parameters are the basic building blocks for any successful javascript.
Share the workload
================
It may seem ironic at first, but 3 short functions are more efficient than one long procedural function. Especially if tasks get repeated. This becomes more important if you start making methods and objects of your own.
Global variables
==============
As you know that all global variables are also properties of the window object? It means that we can create global variables from inside a function. In fact, let’s make a function that exists JUST to create new global variables
function makeNewGlobal( varName, val )
{
window[varName] = val;
}makeNewGlobal( “greeting”, “Hello World!” );
alert( greeting ); // Alerts ‘Hello World!’
Create references
=============
If you have any code that accesses a DOM object that you need to use more than once, create a reference. It’s for more efficient than running getElementbyId() a bunch of times, or accessing your object via some collection such as images or links.
// Bad way
function changeObject( oId )
{
document.getElementById( oId ).className = ‘blah’;
document.getElementById( oId ).setAttribute( “alt”, “new text” );
}// Good way
function changeObject( oId )
{
var o = document.getElementById( oId );
o.className = ‘blah’;
o.setAttribute( “alt”, “new text” );
}
The parseInt() function
====================
A very handy function indeed, but what happens here?
var myString = “010″;
var myNum = parseInt( myString );
Does myNum now equal 10? No. myNum is now equal to 8. Why? Becase parsenInt does it’s best to guess the proper radix based on the input (8, 10, or 16), and a number like 010 looks octal. It’s the leading zero in the string that trips up parseInt() here. It is not very well known that parseInt can take a second parameter. You guessed it, the radix.
var myString = “010″;
var myNum = parseInt( myString, 10 );
This gives us what we expect, myNum is now equal to 10.
Popup Window Links
==================
If you are making a link to a popup window, I highly suggest this format
<a href=”whateverPage.htm” target=”new” onclick=”window.open( this.href, this.target, ‘whatever features you want here’ ); return false;”>Click here!</a>
This differs somewhat from using the java script: pseudo-protocol or just putting a hash (#) in the href. The method above will still allow the link to be usable if the user has javascript turned off and more importantly, search engine spiders can follow this link
Creating HTML strings
===================
If you are creating HTML as a string whether performing an innerHTML operation or whatever, use single quotes to delimit the HTML string. Why? Because proper HTML should have double quotes around attribute values, and using single quotes to delimit the HTML keeps you from having to do lots of escaping.
Conditionals
==========
If you are doing some sort of comparison conditional, where one operand of that conditional is a literal, like if
( someVar == “someString” ) or if ( myNum == 3 )
it’s actually better to list the literal operand first:
if ( “someString” == someVar )
if ( 3 == myNum )
Why? Because if you mistype the equality operator (==) and instead type the assignment operator (=) — a fairly common typo, then you will discover this error at runtime. Tracking down the cause of these errors can be difficult, but switch the order of your operands and the mistake of assigning a variable to a literal error instantly and give a useful line-number (even in IE!)
The hidden power of setTimeout
===========================
The first argument for the setTimeout (and setInterval) function doesn’t have to be a string. In fact, it is much more powerful when you send a function pointer, or, a reference to a function (passing it by name), instead.
So, instead of
setTimeout( “loop()”, 1000 );
do it this way
setTimeout( loop, 1000 );
Now, if we get creative, we can solve the issue of passing arguments to a setTimeout-called function, which I’ve seen many times. As some of you know, the variables you are trying to pass will lose scope (unless they are global). The method to our madness will be the anonymous function.
Once again, instead of
setTimeout( “loop(counter)”, 1000 );
We can use
setTimeout( function() { loop(counter); }, 1000 );
I know what you’re thinking — “Why can’t I use setTimeout( loop(counter), 1000 ) ???”. Because This is a function call, and we need to pass a function pointer. Since we declare an anonymous function that itself calls loop(), then we are legitimately passing the proper reference, AND maintaining the power to call the function.
Filed under: JavaScript, Tips & Tricks

JavaScript requires semicolon – if you don’t specify the semi-colons, javascript will automatically insert them. This is called semi-colon insertion – and it can cause trouble sometimes.
Nice post, by the way.
A few corrections:
1.) NEVER specify the language attribute. Since each browsers support varies, it is totally useless.
2.) why create a function to create a global variable… just do
foo = ‘this works’;
or window.foo = ‘this works too’;
3.) passing additional parameters to .setTimeout() and .setInterval() actually works just fine in all modern browsers, but since IE is stuck in the dark ages, you can’t us them on a site that must support IE.
For a good resource on bugs in IE (or any browser), check out this site:
http://webbugtrack.blogspot.com/