Arriving at JavaScript from a C# and Java background, I am surprised to see the below snippet of code works. The variable s
as I return it from the sum
function should not exist in this scope.
How does JavaScript scope work in the following example? The scope of s
should be limited to inside the for
loop but not after its closing curly bracket. The equivalent snippet in Java or C# will state something like s does not exist in the current context.
function sum(arr) {
for(var i = 0, s = 0; i < arr.length; s += arr[i++]) {
// scope of s is okay here
}
return s; // but, shouldn't this be a violation of scope?
}
// some test code
var data = [1,2,3,4];
var total = sum(data);
console.log(total);