Get the last item in an array

Get the last item in an array

Here is my JavaScript code so far:
var linkElement = document.getElementById(“BackButton”);
var loc_array = document.location.href.split(‘/’);
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));

Currently it takes the second to last item in the array from the URL. However I want to do a check for the last item in the array to be “index.html” and if so, grab the third to last item instead.


Solution 1:

if(loc_array[loc_array.length-1] == 'index.html'){
 //do something
 //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:




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.


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];

Solution 5:

Two options are:

var last = arr[arr.length - 1]


var last = arr.slice(-1)[0]

The former is faster, but the latter looks nicer

Solution 6:

Here’s how to get it with no effect on the original ARRAY

a = [1,2,5,6,1,874,98,"abc"];
a.length; //returns 8 elements

If you use pop(), it will modify your array

a.pop();  // will return "abc" AND REMOVES IT from the array 
a.length; // returns 7

But you can use this so it has no effect on the original array:

a.slice(-1).pop(); // will return "abc" won't do modify the array 
                   // because slice creates a new array object 
a.length;          // returns 8; no modification and you've got you last element