Andrew said:
If I have some code in a function that looks something
like this:
if (x) {
for (var i = 0; i < a; i++) {
//blah
}
} else {
for (var i = 0; i < b; i++) {
//blah
}
}
JSLint tells me that "Identifier 'i' already declared
as var" but I thought it was correct practice to stick
'var' in front of the variable in a FOR statement's
initialiser. What is the correct use of 'var' in this
situation?
Some languages, such a Java, are block-scoped and declaring variables
within - for - makes those variables only visible within the following
block. When following the general programming axiom that no variable
should be given more scope than it absolutely needs you would want the -
i - variables to be scoped to just the - for - blocks, and so have to
declare the variable for each block.
The scoping units of javascript are functions. If a variable is declared
within a function (and at any point within that function) then it is
visible to the entire function and declared from the moment the function
starts to execute. (As javascript enters then execution contexts of a
function, for each variable declaration within a function body, a named
property is created on the Variable/Activation object for that execution
context (a process called "variable instantiation"), providing the local
variables for the execution of the function). It doesn't matter where
within a function body a variable declaration is to be found, the
resulting local variables exist prior to the execution of the first
statement within the function. (Initial local variable creation does not
include the assignment of (non-default) values to those variables, the
values are not assigned until the assignment expressions within the
function body are executed).
The practical upshot of putting - var i - in each - for - statement is
that the - i - variable is declared twice within the same scope (and it
is this that JSLint is objecting to). In practice all javascript does
when a variable is declared twice in the same scope is to repeat the
process of variable instantiation for that variable, which will not
effect how the subsequent code executes.
It is widely felt (and this is opinion, though often informed by
experience) that local variables should be declared at the beginning of
the scope to which they apply, and once only. In javascript that would
mean declaring all function local variables at the start of a function
body. JSLint's attitude is a push in this sort of 'best practice'
direction, rather than a requirement of the language itself.
Richard.