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
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);