For Loops: "Less than" or "Less than or equal to"?

Hello, this is a simple question but one that’s been bugging me while doing the Profile Lookup challenge.
In a for loop ( for ( var i = 0; i < contacts.length; i++)), why is the “i” stopped when it’s less than the length of the array and not less than or equal to (<=)? Shouldn’t the for loop continue until the end of the array, not before it ends?

The index of the last element in any array is always its length minus 1. With i < contacts.length, you’re telling the loop to only count up to the integer before that length, which is the index of the last element.

1 Like

I see where my confusion came from! On the challenge “Iterate Through an Array with a For Loop”, I accidentally put “ourArr” instead of “myArr” and then thought I was clever to use a <=. The challenge passed, but only because ourArr just happened to be one parameter shorter than myArr! Thank you for your help!

// Example
var ourArr = [ 9, 10, 11, 12];
var ourTotal = 0;

for (var i = 0; i < ourArr.length; i++) {
ourTotal += ourArr[i];
}

// Setup
var myArr = [ 2, 3, 4, 5, 6];

// Only change code below this line
var total = 0;

for (var i = 0; i <= ourArr.length; i++) {
total += myArr[i];
}

1 Like

Arrays start with index 0 , so if you have 10 elements in your array, the last index would be 9; that’s why the last index of an array is always length -1 . Hope that helps clarify.