08
Nov
07

Javacript hint: ‘var’ ist your friend!

A few times I came across a surprising habit of Javascript which is a bit confusing for PHP developers.

Javascript places properties into the global scope (the window object in case of a website) if you declare a variable without the ‘var’ keyword.

function f() {
localvar = local;
}
f();
alert(localvar);

will result in local.

If you replace the line
localvar = local by
var localvar = local

the script results in undefined

This can lead to really interesting effects when having nested loops like this:

for(i=0; i<somvar.length; i++) {
dosomemagic();
}

In this case i is placed in global scope and gets overwritten by a nested loop with the same construction. Make sure that you always use the correct version:

for(var i=0; i<somvar.length; i++) {
dosomemagic();
}

In this context it’s worth a note that Javascript does not have a blockscope. Thus the variable i defined the example, continues to live when the loop is finished!


0 Responses to “Javacript hint: ‘var’ ist your friend!”


  1. No Comments

Leave a Reply