0

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);
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
ThisClark
  • 14,352
  • 10
  • 69
  • 100
  • Also, [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Alexander O'Mara Mar 05 '17 at 07:45
  • Thanks - it's the *No such thing as block scope in JavaScript* part that got me. – ThisClark Mar 05 '17 at 07:47
  • The problem with the accepted duplicate answer is its lack of explanations, but the example tells me why it works the way it does. I can't explain it in language terminology, but I get how it works now. – ThisClark Mar 05 '17 at 07:50
  • See also Hoisting - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var – ThisClark Mar 05 '17 at 17:47

0 Answers0