Preloader
Javascript
  • Estimated reading time: 1 Minute

How to check if an element of an array is the last within a loop in Javascript

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 !

Share:
Carlos Delgado

Carlos Delgado

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.

Related articles
JavaScript vs. Python for Data Analysis: Key Differences
30 Jan, 2026
  • Estimated reading time: 5 Minutes
Is Framevuerk Still Relevant in 2026?
3 Jan, 2026
  • Estimated reading time: 5 Minutes
The Best JavaScript i18n Libraries Compared
31 Oct, 2025
  • Estimated reading time: 8 Minutes
How to Build a Simple Photo Editor in the Browser with JavaScript
14 Sep, 2025
  • Estimated reading time: 5 Minutes
Our Sponsors

Our blog is proudly supported by industry-leading sponsors.