Detect last iteration in FOR OF loop in ES6 javascript

One approach is using Array.prototype.entries():

for (const [i, value] of arr.entries()) {
    if (i === arr.length - 1) {
        // do your thing
    }
}

Another way is keeping a count outside the loop like Shidersz suggested. I don’t think you want to check indexOf(item) though because that poses a problem if the last item is duplicated somewhere else in the array…

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)