javascript array check if last element code example

Example 1: how to check the last item in an array javascript

const colors = ['red', 'yellow', 'green', 'blue']
const lastItem = colors[colors.length - 1]
console.log(lastItem)

Example 2: js detect end of array

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);
    }
}

Example 3: js detect end of array

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);
    }
}