0

Could someone explain to me why this doesn't work? At first, I thought it was because Javascript closures but I'm not so sure

let accounts = [];
accounts[0] = 30;
accounts[1] = 25;
accounts[2] = 45;

var totalBalance = accounts.forEach(function(obj){
    totalBalance += obj;
    console.log(totalBalance)
})

console.log(totalBalance);

The output of this last console.log is undefined

Myst
  • 7
  • 3
  • 3
    simple reason: `forEach` returns `undefined`. And that's the last thing written to `totalBalance`. Either loop and inside the loop write to `totalBalance` but don't assign the result of `forEach` to it or use a `reduce` which *does* return a value and assign that result to `totalBalance`. – VLAZ Jun 23 '22 at 13:21

1 Answers1

0

Because you're not assigning a function to totalBalance, you're assigning whatever forEach returns. Let's check in the documentation?

Return value
undefined.

Therefore, it only makes sense that your variable is undefined. Here, this works better:

let accounts = [];
accounts[0] = 30;
accounts[1] = 25;
accounts[2] = 45;

var totalBalance = 0; 
accounts.forEach(function(obj){
    totalBalance += obj;
    console.log(totalBalance)
})

console.log(totalBalance);
BNazaruk
  • 6,300
  • 3
  • 19
  • 33