Learn how to check in a for or while loop, if the iteration is the last in the array

The comparison that we need to make to check if an iteration is the last within an array, can vary according to the way you iterate.

For loop

To check wheter an iteration is the last in the loop or not, we only need to know the length of the array. Based on this number, we will make a comparison between the length of the array (total items inside) and the current iteration index (the index of the item inside of the array) plus one, because as everybody knows, the first element of the array is always 0 as it's exactly contained in the memory location that array refers (0 elements away). If these values are equal, then it's the last iteration.

For example, to check within a for loop you only need to check the previous rule using an if statement:

var group = ["a","b","c","d"];
var groupLength = group.length;

for(var i = 0;i < groupLength;i++){
    var item = group[i];

    // Do something if is the last iteration of the array
    if((i + 1) == (groupLength)){
        console.log("Last iteration with item : " + item);
    }
}

While loop

As the while loop will start iterating from the last item (in the example the item "d"), we need to check if the value that decreases (the counter of the index to handle) is equal to 0.

var group = ["a","b","c","d"];
var groupLength = group.length;

while (groupLength--) {
    var item = group[groupLength];

    if(groupLength == 0){
        console.log("Last iteration with item : " + item);
    }
}

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors