When you write complex-enough software, you will often need to get the last element of an array.
For this post, we'll be using the following array as the example:
const array = [1, 2, 3, 4, 5];
This array has
5 elements. We can confirm that by using the
const array = [1, 2, 3, 4, 5]; console.log(array.length); // 5
For example, since arrays are zero-index, you can get the first element of the array by using the
const array = [1, 2, 3, 4, 5]; console.log(array); // 1
Therefore, if we want to get the last element of an array, we must pass it the index equal to the length of the array minus one. The minus one accounts for the fact that the first element has an index of
0 instead of
const array = [1, 2, 3, 4, 5]; const lastElement = array[array.length - 1]; console.log(lastElement); // 5
In this post, we've seen the best way to get the last element of an array is to use the
.length property and the
[index] syntax to get the element.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!