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

185
Views
Get right value for instance variable outside of for loop, but not inside

I am a JavaScript begginer and don't understand why when I create instances of a class and store them in an array I can access the instance variables outside of a for loop and get the correct value, but inside a for loop it doesn't work as anticipated.

class TestClass{
    constructor(foo){
        this.foo = foo;
    }
}

var classArray = [];

for (var i=0; i<10; i++){
    classArray.push(new TestClass(i));
}
var total = 0;
for (obj in classArray){
    total += obj.foo;
}

console.log(total);
console.log(classArray[0].foo);

This gives the output of:

NaN
0

The 0 is as I would have expected, but I don't see why it gives NaN for the summation. Any help would be appreciated, thank you.

about 4 years ago · Santiago Gelvez
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!