Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
Declaring variable with inside function to define its value

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!