Get the Last Element of the Array in JavaScript

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

In this tutorial, we are going to learn about how to get the last element in an array using JavaScript.
In this tutorial, we show you two ways to get the last element in an array using JavaScript.
  1. Using array.length property
  2. Using slice() method

1. Using array.length property

In array, we have a length property by using that we can find how many elements present in an array if we subtract arr.length-1 we can get the last element.
Example:
let elements = [1,2,3,4,5,6,7,8,9]; const lastElement = elements[elements.length-1]; console.log(lastElement); 
Output:
9

2. Using slice() method

The slice() method returns the selected elements in an array, as a new array object.
If we pass -1 as an argument to the slice method we can get the last element in an array.
Example:
let elements = [1,2,3,4,5,6,7,8,9]; const lastElement = elements.slice(-1); console.log(lastElement); 
Output:
[9]

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare