0

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]);
2
  • Simply console logging i would give you the answer. Commented Nov 24, 2013 at 2:55
  • 1
    Hint: if i < array.length returns true, you'd still be in your for loop. Commented Nov 24, 2013 at 2:57

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.