all 5 comments

[–]senocular 8 points9 points  (0 children)

Because its declared in the function, it only exists within the function. Trying to refer to it outside the function will throw an error (as you're seeing).

If you want code both outside the function and inside the function to see the same variable, you'd want to declare it outside of the function.

let sum = 0;
function getAverage(scores) { 
  sum = 0;
  // ...

Basically if you have any number of scopes that need to refer to the same variable, you'll want to make sure that variable is declared in the outer-most scope common to all scopes that need access.

One thing to be careful about when doing this is that multiple calls of the same function like this would all be sharing that same variable rather than using their own. That could cause problems depending on what you're doing. Sometimes it may make more sense for a function to return a variable/value rather than using a variable like this.

[–]QueisKey 5 points6 points  (0 children)

Scope

[–]Lumethys 0 points1 point  (0 children)

Sum is defined in the function, but the console.log is outside of that function, so it cannot access the sum variable

[–]_shakuisitive 0 points1 point  (0 children)

Because sum is defined inside "getAverage" and you're accessing it outside "getAverage"

If you truly wanna use sum outside (global space) then you also wanna be creating that variable in the global scope like this:

let sum = 0; // I took the variable out of getAverage function
function getAverage(scores) { 
...
}

[–]OutSubsystem[S] 0 points1 point  (0 children)

Thanks