November 22, 2010
I was discussing JavaScript code with a friend and he noticed that I had declared all the variables at the top.
He likes to declare the variable where they are used to be sure that the variable being used is declared with var otherwise that variable will become global variable. This fear of accidentally creating a global variables wants him to see variable declaration next to where it is being used.
var payment;
payment = soldPrice + shippingCost;
In the above case user has declared payment variable in the middle so that he is sure that payment is declared. However if there is a typo as given below then he has accidentally created a global variable "payment".
var payment; //there is a typo
payment = soldPrice + shippingCost;
Having variable declaration next to where variable is being used is not a safe way of guaranteeing that variable is declared. Use the right tool and that would be jslint validation. I use MacVim and I use Javascript Lint. So every time I save a JavaScript file validation is done and I get warning if I am accidentally creating a global variable.
You can configure such that JSLint validation runs when you check your code into git or when you push to github. Or you can have a custom rake task. Many solutions are available choose the one that fits you. But do not rely on manual inspection.
Take a look at following code. One might expect that console.log will print "Neeraj" but the output will be "undefined" . That is because even though you have declaration variables next to where they are being used, browsers lift those declarations to the very top.
name = "Neeraj";
function lab() {
console.log(name);
var name = "John";
console.log(name);
}
lab();
Browser converts above code into one shown below.
name = "Neeraj";
function lab() {
var name = undefined;
console.log(name);
name = "John";
console.log(name);
}
lab();
In order to avoid this kind of mistakes it is preferred to declared variables at the top like this.
name = "Neeraj";
function lab() {
var name = "John";
console.log(name);
console.log(name);
}
lab();
Looking at the first set of code a person might think that
Also remember that scope of variable in JavaScript at the function level.
There are two ways of declaring a function.
var myfunc = function () {};
function myfunc2() {}
In the first case only the variable declaration myfunc
is getting hoisted up.
The definition of myfunc is NOT getting hoisted. In the second case both
variable declaration and function definition is getting hoisted up. For more
information on this refer to my
previous blog on the same topic.
If this blog was helpful, check out our full blog archive.