In this article, I will going to show on how to get the last element of an array in JavaScript, exploring different methods and provide practical example codes.
Methods to Get the Last Element of an Array in JavaScript
To get the last element of an array in JavaScript, you can use different methods.
Let’s probe each of these methods in details.
Method 1: Using the Index array.length – 1
One of the method to get the last element of an array is by using its index.
In JavaScript, arrays are zero-based, that means the first element is located at index 0.
To access the last element, you can use the index array.length – 1.
Here’s an example code:
const array = [10, 20, 30, 40, 50];
const lastElementExample = array[array.length - 1];
console.log(lastElementExample );Output:
50
Method 2: Using the pop() Function
Another method to get the last element of an array is by using the pop() function.
This method eliminate the last element from the array and returns it, allowing you to store it in a variable.
Let’s take a look at an example:
const array = [10, 20, 30, 40, 50];
const lastElementFunction = array.pop();
console.log(lastElementFunction);
console.log(array);
Method 3: Using Array Destructuring
JavaScript supports array destructuring, which enables you to extract values from arrays into individual variables.
By using this feature, you can easily get the last element of an array.
Here’s how you can do this:
const arraySample = [11, 12, 13, 14, 15];
const [, , , , lastElementSample] = arraySample;
console.log(lastElementSample);
Method 4: Using the slice() Function
The slice() function in JavaScript enables you to extract a portion of an array and return it as a new array.
By passing a negative index to slice(), you can extract the last element.
Here’s an example code:
const exampleArray = [10, 20, 30, 40, 50];
const lastElementSample = exampleArray.slice(-1)[0];
console.log(lastElementSample);
Frequently Asked Questions
To check if an array is empty in JavaScript, you can use the length property. If the length of the array is zero, that means the array is empty.
There are several methods to add elements to an array in JavaScript. You can use the push() method to add elements to the end of an array or the unshift() method to add elements to the beginning.
Yes, you can modify the last element of an array directly by accessing it through its index. Since arrays in JavaScript are mutable, you can assign a new value to the last element using the index array.length – 1.
To remove the last element from an array in JavaScript, you can use the pop() method. This method removes the last element and returns it, enabling you to store it in a variable if needed.
Conclusion
In JavaScript, getting the last element of an array is a frequent operation. By using the methods discussed in this article, you can easily access the last element of an array based on your specific requirements.
Remember, you can use the index, pop() method, array destructuring, or the slice() method to get the last element.
Each method provides its own advantages, so choose the one that fits your coding style and the context in which you are working.
Additional Resources
- How to Get Timezone in JavaScript
- How to disable button in JavaScript
- How to create a stopwatch in JavaScript
Quick step-by-step summary (click to expand)
- Methods to Get the Last Element of an Array in JavaScript. Read the ‘Methods to Get the Last Element of an Array in JavaScript’ section for the details and code.
- Conclusion. Read the ‘Conclusion’ section for the details and code.
- Additional Resources. Read the ‘Additional Resources’ section for the details and code.
Common use cases for How to get last element of array
How to get last element of array is one of the most-used tools when working with JavaScript arrays. Typical scenarios:
- Transforming data for the UI. Convert an array of API records into an array of display strings or React components.
- Filtering large datasets. Remove entries that do not match a condition before passing them to another function.
- Aggregating totals. Sum, count, or group values from arrays of orders, events, or measurements.
- Chaining transformations. Combine map, filter, and reduce to express complex logic in a single readable pipeline.
- Preparing input for storage. Convert in-memory arrays to a format that JSON serialization or a backend endpoint can consume.
Working code example
A practical example showing How to get last element of array in a complete workflow:
// Fetch an array of orders, transform, and total the results
const orders = [
{ id: 1, item: "book", price: 12, quantity: 2 },
{ id: 2, item: "pen", price: 3, quantity: 5 },
{ id: 3, item: "notebook", price: 8, quantity: 1 }
];
const total = orders
.filter(order => order.quantity > 0)
.map(order => order.price * order.quantity)
.reduce((sum, subtotal) => sum + subtotal, 0);
console.log("Grand total:", total); // 47
Common pitfalls with How to get last element of array
- Mutating the original array. Some methods like sort() and reverse() modify in place, others like map() return a new array. Confirm which one you are using.
- Missing return statement. In map() and filter() callbacks, forgetting the return produces undefined values or a filter that keeps everything.
- Chaining on undefined. If an intermediate result is undefined (empty API response), the chain crashes. Add null checks or default to an empty array.
- Performance on large arrays. Multiple chained methods each create new arrays. For arrays with 100k+ elements, use a single for loop instead.
Best practices for How to get last element of array
- Use const for iteration variables. In callback params like (order) => …, use const semantics unless you truly reassign.
- Prefer named callbacks for reuse. Extract the predicate into a named function if it appears in more than one place.
- Explicit accumulator initial value. Always pass 0, [], or {} as the initial value to reduce() to avoid the first-element-as-accumulator quirk.
- TypeScript for large codebases. Add types to array elements so the compiler catches wrong-property errors at design time.
