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.
Use the right tool
1var payment; 2payment = 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".
1var payment; //there is a typo 2payment = 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.
Variable declaration are being moved to the top by the browser
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.
1name = "Neeraj"; 2function lab() { 3 console.log(name); 4 var name = "John"; 5 console.log(name); 6} 7lab();
Browser converts above code into one shown below.
1name = "Neeraj"; 2function lab() { 3 var name = undefined; 4 console.log(name); 5 name = "John"; 6 console.log(name); 7} 8lab();
In order to avoid this kind of mistakes it is preferred to declared variables at the top like this.
1name = "Neeraj"; 2function lab() { 3 var name = "John"; 4 console.log(name); 5 console.log(name); 6} 7lab();
Looking at the first set of code a person might think that
Also remember that scope of variable in JavaScript at the function level.
Implications on how functions are declared
There are two ways of declaring a function.
1var myfunc = function () {}; 2function 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.