Skip to content

Why to declare JavaScript Variables On Top of Functions

Updated: at 11:18 PM

I make this mistake over and over.  It took me years to learn to declare variables NOT at the top of functions but to declare them close to where I use them.  Well, not so much the case in JavaScript.  Say for example you have two for loops that operate on the same variables.   My expectation from years of experience is to do the following:

for (var i = 1; i <= 10; i++) {
var itemIdQuery = "#col" + i;
var panel = Ext.ComponentQuery.query(itemIdQuery)[0];
if (panel.isVisible()) {
visibleTimeColumns++;
}
}

for (var i = 1; i <= 10; i++) {
var itemIdQuery = "#col" + i;
var panel = Ext.ComponentQuery.query(itemIdQuery)[0];
}

Well, I think it works but only by accident.  Resharper reminds me that I’m reinstantiating an  already existing variable (itemIdQuery and panel).  What I really should do is the following:
 
var panel;
var visibleTimeColumns = 0;
var i;
for (i = 1; i <= 10; i++) {
itemIdQuery = "#col" + i;
panel = Ext.ComponentQuery.query(itemIdQuery)[0];
if (panel.isVisible()) {
visibleTimeColumns++;
}
}

for (i = 1; i <= 10; i++) {
itemIdQuery = "#col" + i;
panel = Ext.ComponentQuery.query(itemIdQuery)[0];
}

HTH’s.