How do I access the last element of an array?



How do I access the last element of the array?


Say you have an array assigned to the variable exampleArray. You can use the length property of the array, which will give you the number of elements in the array. However, since arrays’ index start at 0, you will need to subtract 1.

exampleArray[exampleArray.length - 1]


When our toolbox is still rather bare, the length attribute method above is what we have to reach for. However, as we gain more knowledge of the built in functions. we can reach for them, as well…

 > [1,2,3,4,5].slice(-1)
=> [5]
 > [1,2,3,4,5].slice(-1)[0]
=> 5

Once we get into arrays is a good time to look up this method. Array.prototype.slice()