0

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.

  • 1
    because `obj` wll be `0`, `1`, `2`, ... `9` - the keys(indices) of the array, and they don't have a `.foo` property ... you want the values in classArray ... so, `for...of` not `for...in` – Jaromanda X Jul 15 '22 at 23:22
  • Jaromanda X, thank you. I didn't realise there was 'in' and 'of' in JavaScript. – KrustyKnuckles Jul 15 '22 at 23:25

0 Answers0