Get Last Element of Array JavaScript: Practical Guide

A practical guide to retrieving the last element of a JavaScript array with traditional bracket notation and modern arr.at(-1), plus edge cases, performance notes, and real-world examples.

JavaScripting
JavaScripting Team
·5 min read
Quick AnswerDefinition

To get the last element of an array in JavaScript, use arr[arr.length - 1], which works everywhere. For modern environments, you can also use arr.at(-1). If the array is empty, both return undefined; guard with a default if needed (e.g., arr.at(-1) ?? defaultValue). Remember that arr.length-1 is a computed index, so it won't throw if length is zero—it will yield undefined.

Core concepts: Access patterns for the last element

Understanding how to reliably obtain the last element of an array in JavaScript is fundamental. The approaches differ mainly in syntax and readability, but the intent is the same: pick the item at index length-1. This section demonstrates the traditional bracket approach and how it scales to edge cases. We'll start with a simple example:

JavaScript
const nums = [10, 20, 30, 40]; const last = nums[nums.length - 1]; console.log(last); // 40

Why this matters: it works everywhere, including older runtimes without newer features. If you pass an empty array, the result is undefined, which you should guard against in real code.

The bracket notation: arr[arr.length - 1] in detail

The classic pattern arr[arr.length - 1] calculates the last index and returns the value. It is straightforward and fast, but requires you to manually handle the empty array case. Here's another example with a guard:

JavaScript
const a = []; const last = a.length ? a[a.length - 1] : undefined; console.log(last); // undefined

You can also combine with a default:

JavaScript
const lastOrDefault = (a.length ? a[a.length - 1] : 'none');

Modern approach: Array.prototype.at for negative indices

ES2022 introduced Array.prototype.at, which lets you use negative indices to reach from the end. This makes code more readable when you want the last element without computing length. Use it when you target modern runtimes:

JavaScript
const items = [1, 2, 3, 4]; console.log(items.at(-1)); // 4

Note: translate to older environments with a fallback if needed, e.g., (arr.at(-1) ?? defaultValue) or the bracket pattern.

Edge cases: empty, sparse arrays and defaults

Arrays can be empty or sparse; you still need to handle the last element safely. For an empty array, both bracket and at return undefined. For sparse arrays like [1, , 3], the last element is 3 and length is 3. Examples:

JavaScript
const empty = []; console.log(empty[empty.length - 1]); // undefined
JavaScript
const sparse = [1, , 3]; console.log(sparse.at(-1)); // 3

Guard patterns:

JavaScript
const lastSafe = a.length ? a[a.length - 1] : undefined;

Performance and readability: which method to use

In most codepaths, readability matters more than micro-b performance. The bracket method is extremely fast and widely supported. The at(-1) method improves readability, especially when accessing from the end in longer chains. A tiny micro-benchmark illustrates the idea:

JavaScript
function lastBracket(arr){ return arr[arr.length - 1]; } function lastAt(arr){ return arr.at(-1); }
JavaScript
const arr = Array.from({length: 1000}, (_,i)=>i); console.time('bracket'); for(let i=0; i<100000; i++){ lastBracket(arr); } console.timeEnd('bracket'); console.time('at'); for(let i=0; i<100000; i++){ lastAt(arr); } console.timeEnd('at');

Interpretation: both are fast enough for typical UI work; prefer arr.at(-1) for clarity when supported.

Practical patterns: using last element in data processing

Working with API responses or streams often ends with the last item being the most relevant, e.g., the most recent log entry. Retrieving it with a single expression keeps code concise:

JavaScript
const logs = fetch('/api/logs').then(r => r.json()); logs.then(entries => { const latest = (entries?.length ? entries.at(-1) : null); console.log(latest); });

Another common scenario: getting the last user from a list of users returned from an API:

JavaScript
const users = [ {id:1, name:'Alice'}, {id:2, name:'Bob'}, {id:3, name:'Carol'} ]; const lastUser = users.at(-1); console.log(lastUser.name); // Carol

Steps

Estimated time: 60-90 minutes

  1. 1

    Choose the access method

    Decide between bracket notation (arr[arr.length - 1]) and the modern at(-1). Consider environment compatibility and readability.

    Tip: Prefer arr.at(-1) when targeting modern runtimes for clarity.
  2. 2

    Write the basic access

    Implement the access expression in a small, testable snippet to confirm it returns the expected value.

    Tip: Test with both non-empty and empty arrays.
  3. 3

    Guard against empty arrays

    Add a guard or default to avoid undefined in downstream logic.

    Tip: Use ?? to provide defaults when appropriate.
  4. 4

    Consider edge cases

    Check sparse arrays and ensure the last index behavior aligns with expectations.

    Tip: A hole in a sparse array still makes length reflect the final index.
  5. 5

    Document and optimize

    Add comments and consider a small performance note if used inside hot paths.

    Tip: Keep the code readable and maintainable.
Pro Tip: Use arr.at(-1) for readability when you know the environment supports ES2022+.
Warning: Do not assume non-empty arrays; always guard or provide defaults to avoid runtime errors.
Note: In sparse arrays, the last element is determined by the final defined index, not just the length.

Prerequisites

Required

Optional

  • Basic command line knowledge for running scripts
    Optional
  • Optional: TypeScript knowledge for typings (not required)
    Optional

Keyboard Shortcuts

ActionShortcut
CopyInside code blocksCtrl+C
Open DevToolsIn a browser to test snippetsCtrl++I
Find textSearch within the pageCtrl+F
Clear consoleBrowser or Node REPLCtrl+L

Questions & Answers

What is the simplest way to get the last element in JavaScript?

The simplest approach is arr[arr.length - 1], which works in all environments that support arrays. For modern code, arr.at(-1) is even clearer. Always consider empty arrays and provide a default if necessary.

Use arr[arr.length - 1] or arr.at(-1) for the last element; guard against empty arrays.

What happens if the array is empty?

Accessing the last element on an empty array yields undefined with both methods. Guard with a length check or use a default value with the nullish coalescing operator.

An empty array returns undefined; use a guard or default.

Does arr.at(-1) work everywhere?

arr.at(-1) works in modern browsers and Node versions that support ES2022. For older environments, fall back to the bracket pattern or polyfills.

arr.at(-1) is modern; fall back if you need older environments.

How do I handle sparse arrays?

Sparse arrays may have holes but the last defined element can still be retrieved with at(-1) or the bracket form. The length reflects the final index, not always the number of defined elements.

Last element still accessible even if there are holes.

Can TypeScript types affect the last element access?

Yes. In TypeScript, the last element’s type is inferred from the array’s element type. arr.at(-1) is supported in newer TS versions and aligns with your array’s type.

Types align with the array's element type; arr.at(-1) follows TS versions.

Are there performance trade-offs between methods?

Performance differences between arr[arr.length - 1] and arr.at(-1) are negligible for typical UI code. Choose clarity and consistency over micro-optimizations within hot paths.

Performance is usually not a concern; focus on readability.

What to Remember

  • Use arr[arr.length - 1] for broad compatibility.
  • Prefer arr.at(-1) if you target modern runtimes for clarity.
  • Guard empty arrays with a default to avoid undefined values.
  • Sparse arrays preserve last defined element; length may be misleading.
  • Choose readability first, then optimize if needed.

Related Articles