How to get the last element in a JavaScript Array

Let’s say you have an array of numbers (but it could be an array of anything really):

const myNumbers = [1,2,3,4,5]

You want the last number in the array but don’t care how many elements are in the array. The simplest way to get the last number in the array is to get the element who’s position is the same as the length of the array minus 1. The minus 1 is because arrays are zero based, so the first element is accessed like so:

const selectedNumber = myNumbers[0]

Therefore, the easiest way to get the last element from an array without knowing how many elements are in the array is like this:

const lastNumber = myNumbers[myNumbers.length - 1]