简体   繁体   中英

about the scope of forEach method in Javascript

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

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) //prints 110

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM