var sum = function(array) {
var sum = 0; // Declare with var
for (index in array) {
sum += array[index];
}
return sum;
}
...will work. Just referencing sum
causes the engine to look for a variable called sum
firstly inside the function, and if not found there, it will traverse up the object's scope chain to find it. Declaring with var
inside a function tells the engine that this is a new variable with its scope restricted to the direct parent object, in this case, the function.