Function Scope

Using Functions

Function Scope

🙋 Need help? Ask an expert now!

Knowing the scope of the function as well as the variables inside the function is extremely important when writing your program. Every variable has its own scope and can only be used in specific places inside the program. As mentioned previously, there are two types of scopes, the local scope and the global scope. Any variable declared inside the function, including the parameter, is considered a local variable and can only be used within the function.

As mentioned previously, the parameter of the function is a local variable. This is why calling the three statements that are commented in the code will cause an error. The variables sum, array, and counter don't exist in the global level and will be hidden from the program if it is called outside the function. The function and the variable arr are the only two variables that are in the global scope and can be called anywhere in the program.

Edit Me on GitHub!

Application Question

Consider the following code segment:

var arr = [5, 3, 4, 53, 6, 2];
function numberSum(array){
    var sum = 0;
    console.log(arr);         // Statement 1
    for (counter = 0; counter < array.length; counter++){
      sum += array[counter];
    }
    console.log(sum);         // Statement 2
    return sum;
}
console.log(arr);             // Statement 3
console.log(sum);             // Statement 4
console.log(numberSum(arr));  // Statement 5

Which console.log() statement will cause an error?