Get the last item in an array

Solution 1:

Update 13 July 2021

The new at() method allows you to use negative indices to mean "from the end".

You can access the last item of locArray like this:

if (locArray.at(-1) === 'index.html') {
   // do something
} else {
   // something else
}

At time of update, the at() method is supported in Chrome 92+, FireFox 90+, Node 16 and Deno 1.12+

Older answer

if (loc_array[loc_array.length - 1] === 'index.html') {
   // do something
} else {
   // something else
}

In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: .toLowerCase().

Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.

Solution 2:

Not sure if there's a drawback, but this seems quite concise:

arr.slice(-1)[0] 

or

arr.slice(-1).pop()

Both will return undefined if the array is empty.

Solution 3:

Use Array.pop:

var lastItem = anArray.pop();

Important : This returns the last element and removes it from the array

Solution 4:

A shorter version of what @chaiguy posted:

Array.prototype.last = function() {
    return this[this.length - 1];
}

Reading the -1 index returns undefined already.

EDIT:

These days the preference seems to be using modules and to avoid touching the prototype or using a global namespace.

export function last(array) {
    return array[array.length - 1];
}