How to get the Last Element in a JavaScript Array
Table of Contents
When you write complex-enough software, you will often need to get the last element of an array.
In this post, we'll learn how to get the last element of an array in JavaScript.
For this post, we'll be using the following array as the example:
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
This array has 5
elements. We can confirm that by using the .length
property:
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
console.log(array.length); // 5
We also know that in JavaScript, you can use brackets with the index of the element you want to get from an array.
For example, since arrays are zero-index, you can get the first element of the array by using the [0]
index:
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
console.log(array[0]); // 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 1
.
This is how you get the last element of an array in JavaScript:
JAVASCRIPTconst array = [1, 2, 3, 4, 5];
const lastElement = array[array.length - 1];
console.log(lastElement); // 5
Conclusion
Getting the last element of an array is a common task in JavaScript.
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.
Hopefully, this helped you with your JavaScript journey!
Thanks for reading!
- Getting Started with Solid
- Getting Started with Express
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- Getting Started with Deno
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase