Search code examples
javascriptfunctionvariablesscopeexecutioncontext

Question about the local and global scope -JavaScipt


First time poster here be gentle to my soul. And also sorry if you don't understand me, I'm not a native English speaker.

Here is my code and I'll try to explain what I don't understand below it.


var numbers = [1, 2, 3, 4, 5]; 
var total = 0; 
i = 0;

function averageValue(numbers) { 
  var averageValue = 0; 
  if (numbers.length > 0) { 
    for (i = 0; i < numbers.length; i++) { 
      total += numbers[i]; 
    } 
    averageValue = total / numbers.length; 
  } 
  return averageValue; 
} 
var average = averageValue(numbers);

console.log(total);
console.log(i);

I get what the code is doing that is not the problem but what I don't understand is why doesn't the console.log method make the variables - total and i as 0 - but instead as 15 and 5. I just recently studied about the JavaScript scope and I was under the impression that global scope can't access the local scope, so why can it do just that in this situation. I'm a newbie coder and probably thinking just silly, but I would really appreciate any help.


Solution

  • total and i are declared (with var and as an implicit global respectively) outside the function.

    The function then accesses them. It does not redeclare them with var (which would create new variables with the same name in a narrower scope). The function alters the values of the existing variables.


    If the variables were declared inside the function, then code outside the function couldn't access them. You would get an exception instead:

    var numbers = [1, 2, 3, 4, 5];
    
    function averageValue(numbers) {
      var total = 0;
      var i = 0;
    
      var averageValue = 0;
      if (numbers.length > 0) {
        for (i = 0; i < numbers.length; i++) {
          total += numbers[i];
        }
        averageValue = total / numbers.length;
      }
      return averageValue;
    }
    var average = averageValue(numbers);
    
    console.log(total);
    console.log(i);

    And if you had the variables declared inside and outside the function, then the code in the function would only operate on the local ones, leaving the ones in the wider scope unchanged:

    var numbers = [1, 2, 3, 4, 5];
    var total = 0;
    i = 0;
    
    function averageValue(numbers) {
      var total = 0;
      var i = 0;
    
      var averageValue = 0;
      if (numbers.length > 0) {
        for (i = 0; i < numbers.length; i++) {
          total += numbers[i];
        }
        averageValue = total / numbers.length;
      }
      return averageValue;
    }
    var average = averageValue(numbers);
    
    console.log(total);
    console.log(i);