Reputation: 3635
I have written this bit of code that sums the values of array. Can some one please explain why I'm getting undefined in the last console.log statement.
var array = [2,3,4,5,6,7];
var sum = 0;
for(var i = 0; i < array.length; i++) {
sum = array[i] + sum;
}
console.log(sum);
console.log(array[i]);
Upvotes: 0
Views: 87
Reputation: 276286
That's because the loop performed i++
and now i
is equal to array.length
.
JavaScript returns the primitive value undefined
when you're trying to access object properties that were not previously defined.
The array however is only filled between places 0
and array.length - 1
since JavaScript arrays are 0 based.
Upvotes: 5