How to get last element of array in JavaScript

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

How do I check if an array is empty in JavaScript?

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.

How can I add elements to an array in JavaScript?

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.

Can I modify the last element of an array directly?

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.

How can I remove the last element from an array?

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

Quick step-by-step summary (click to expand)
  1. 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.
  2. Conclusion. Read the ‘Conclusion’ section for the details and code.
  3. 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.

Frequently Asked Questions

What is How to get last element of array in JavaScript?
How to get last element of array is a JavaScript array method or pattern used to transform, filter, or aggregate arrays. It runs on any array and typically returns a new array or a single value, leaving the original untouched (except for a few in-place methods like sort() and reverse()).
How do I use How to get last element of array?
Call How to get last element of array directly on an array with the appropriate callback or arguments. Most modern examples use arrow functions for the callback because they read cleanly and inherit the outer this binding.
Does How to get last element of array mutate the original array?
Most JavaScript array methods return a new array (map, filter, reduce, slice, concat). A few mutate in place (sort, reverse, splice, push, pop). Check the MDN docs for the exact behavior before chaining.
How do I chain How to get last element of array with other array methods?
Chain by calling each method on the return value of the previous one: arr.filter(f).map(g).reduce(h, 0). Because filter and map return new arrays, chaining creates intermediate arrays. For 100k+ element arrays, prefer a single for loop for performance.
Is How to get last element of array slow on large arrays?
For arrays under about 10,000 items, the overhead is negligible. Beyond that, chained array methods create intermediate arrays that add memory pressure. A single for loop is typically 2-5x faster for very large datasets.

Adones Evangelista


Programmer & Technical Writer at PIES IT Solution

Adones Evangelista is a programmer and writer at PIES IT Solution, author of over 900 tutorials and error-fix guides at itsourcecode.com. Specializes in JavaScript, Django, Laravel, and Python error debugging covering ValueError, TypeError, AttributeError, ModuleNotFoundError, and RuntimeError, plus C/C++ and PHP capstone projects for BSIT students.

Expertise: JavaScript · Python · Django · Laravel · Error Debugging · C/C++
 · View all posts by Adones Evangelista →

Leave a Comment