Reputation: 3
I'm a beginner trying to learn to code in javascript. I'm sorry to ask such basic question but I've read a lot of ressources and I still struggle to understand the following behaviour about the scope of the forEach() method (and maybe other methods?).
Consider an array of numbers. I want to calculate the sum of the numbers in the array.
So I declare and initialize a variable called sum.
Then I use the forEach() method to calculate the sum of the items and put the result in the sum variable
Then I console.log(sum).
What I don't understand is why console.log can access the sum variable inside the forEach() function? I thought it would print 0, because console.log is outside the local scope of the forEach() method. I understand the variable sum has global scope, but wouldn't the calculation inside forEach() have local scope?
Thanks for your help.
let arrayOfNumbers = [1, 5 ,9, 16, 34, 45]
let sum = 0;
arrayOfNumbers.forEach(function(item) {
sum = sum + item;
})
console.log(sum) //prints 110
Upvotes: 0
Views: 776
Reputation: 89
Since you declared the variable sum outside the .forEach() loop each interaction will increment the sum variable that's outside the loop. So when you console.log() it will print 110.
If you redeclare (see example below) the same variable using let sum = 0
inside .forEach() it will be reset at every interaction and after the loop finishes it will print '0' again since another instance of the variable was used inside the loop.
let arrayOfNumbers = [1, 5 ,9, 16, 34, 45]
let sum = 0;
arrayOfNumbers.forEach(function(item) {
let sum = 0;
sum = sum + item;
console.log(sum)
})
console.log(sum)
Upvotes: 0
Reputation: 36
Ther reason why console.log can have access to sum value is because when you create a callback inside forEach loop/iteration if you're not giving second argument it will refer to where the function is called.Because callback with function declaration is bound to the object that invokes the function.
So to sum up, the forEach method in this case is running in global scope. To prove this concept, you can try this :
let arrayOfNumbers = [1, 5 ,9, 16, 34, 45]
let sum = 0;
arrayOfNumbers.forEach(function(item) {
console.log(this == window);
sum = sum + item;
})
console.log(sum) //prints 110
Upvotes: 0
Reputation: 39
You have not defined sum in the for each loop. You have instantiated sum it above the loop's scope.
Since the loop is within the scope that sum was defined in the loop is able to mutate sum, this now mutated sum is what you are logging at the end. If you had defined sum within the loop, it would not be defined outside of the loop's scope, and you would get an error when attempting to print it.
Upvotes: 0