Question

Get the Last Array Item in JavaScript

Question

Here is my JavaScript code:

var linkElement = document.getElementById("BackButton");
var locArray = document.location.href.split("/");
var newText = document.createTextNode(
  unescape(capWords(locArray[locArray.length - 2]))
);
linkElement.appendChild(newText);

The code currently gets the second-to-last item in the array created from the URL. How can I check whether the last item is "index.html" and, when it is, get the third-to-last item instead?

Short Answer

You will learn how JavaScript array indexes work from the end of an array, how to conditionally choose an item, and how to safely apply this pattern when reading URL path segments.

Concept

JavaScript arrays use zero-based indexes: the first item is at index 0, the second at 1, and so on. An array also has a length property, which is one greater than its final valid index.

That makes array.length useful for reading items from the end:

  • array[array.length - 1] gets the last item.
  • array[array.length - 2] gets the second-to-last item.
  • array[array.length - 3] gets the third-to-last item.

For the URL requirement, first inspect the last array item. If it is "index.html", choose the item three positions from the end; otherwise, choose the item two positions from the end.

This matters because paths, filenames, lists of messages, page history, and parsed data often have variable lengths. Calculating an index from length lets code work without knowing exactly how many items are present.

Mental Model

Think of an array as a row of numbered lockers. The first locker is numbered 0, but the length tells you how many lockers exist, not the final locker number.

If there are five lockers, length is 5, while the last valid locker is 4. Therefore, subtracting 1 from the length points at the last item. Subtracting 2 moves back one more locker, and subtracting 3 moves back two lockers.

Take Quiz

Syntax and Examples

Use bracket notation with length to access items relative to the end of an array:

const pages = ["products", "shoes", "index.html"];

const last = pages[pages.length - 1];
const secondLast = pages[pages.length - 2];
const thirdLast = pages[pages.length - 3];

console.log(last);       // "index.html"
console.log(secondLast); // "shoes"
console.log(thirdLast);  // "products"

To select a different item based on the final item:

const locArray = ["https:", "", "example.com", "products", "shoes", "index.html"];

const selectedItem = locArray[locArray.length - 1] === "index.html"
  ? locArray[locArray.length - 3]
  : locArray[locArray.length - 2];

console.log(selectedItem); // "products"

The conditional (? :) is a compact if/else. When the last item is "index.html", it uses the third-to-last item. Otherwise, it uses the second-to-last item.

The same code written with if/else can be easier to read:

let selectedItem;

if (locArray[locArray.length - 1] === "index.html") {
  selectedItem = locArray[locArray.length - 3];
} else {
  selectedItem = locArray[locArray.length - 2];
}

Step by Step Execution

Consider this array:

const locArray = ["https:", "", "site.test", "guides", "arrays", "index.html"];
const lastItem = locArray[locArray.length - 1];

let pageName;
if (lastItem === "index.html") {
  pageName = locArray[locArray.length - 3];
} else {
  pageName = locArray[locArray.length - 2];
}

console.log(pageName);

Execution trace:

  1. locArray contains 6 items, so locArray.length is 6.
  2. locArray.length - 1 is 5, so lastItem becomes locArray[5], which is "index.html".
  3. The condition is true.
  4. locArray.length - 3 is 3.
  5. locArray[3] is "guides", so pageName becomes "guides".
  6. The code logs "guides".

If the final item were "arrays" instead, the condition would be false and the code would select the second-to-last item.

Real World Use Cases

Accessing items from the end of an array is common in many situations:

  • URL navigation: Use a parent path segment as a breadcrumb label.
  • File processing: Read a file extension or final filename from a list of path segments.
  • Chat applications: Display the newest message with messages[messages.length - 1].
  • Shopping carts: Inspect the most recently added product.
  • Data imports: Check the final record in a parsed CSV-like list.
  • Version history: Compare the latest version with the one before it.

For browser URLs specifically, the URL API is usually safer than splitting the complete href manually because it separates the hostname, path, query string, and hash correctly.

Take Quiz

Real Codebase Usage

In production code, developers usually avoid repeating index calculations and add validation before accessing positions that may not exist.

A clear helper function for the original rule is:

function getParentLabel(pathSegments) {
  if (pathSegments.length < 2) {
    return null;
  }

  const lastItem = pathSegments[pathSegments.length - 1];
  const offset = lastItem === "index.html" ? 3 : 2;

  return pathSegments.length >= offset
    ? pathSegments[pathSegments.length - offset]
    : null;
}

For a browser location, use URL and remove empty path segments:

const url = new URL(window.location.href);
const segments = url.pathname.split("/").filter(Boolean);
const label = getParentLabel(segments);

if (label !== null) {
  document.getElementById("BackButton").append(
    document.createTextNode(decodeURIComponent(label))
  );
}

This pattern uses a guard clause (return null) for arrays that are too short. It also uses filter(Boolean) to remove empty strings caused by leading or repeated slashes. decodeURIComponent is preferred over the deprecated unescape function for URL-encoded text.

Common Mistakes

Using length as an index

length is not the index of the final item.

const items = ["a", "b", "c"];
console.log(items[items.length]); // undefined

The array has length 3, but its valid indexes are 0, 1, and 2. Use items[items.length - 1].

Forgetting that arrays can be too short

const items = ["index.html"];
console.log(items[items.length - 3]); // undefined

Check that the array has enough items before using an index such as length - 3.

Comparing with assignment instead of equality

if (lastItem = "index.html") {
  // Incorrect: this assigns a value.
}

Use strict equality:

if (lastItem === "index.html") {
  // Correct
}

Splitting the entire URL without considering query strings

const parts = document.location.href.split("/");

A URL like /docs/index.html?mode=print produces a final part containing "index.html?mode=print", not exactly "index.html". Prefer new URL(...).pathname, which excludes the query string and hash.

Assuming every URL ends in a filename

A URL may end with a slash, such as /docs/arrays/. Its final split item may be an empty string. Filter empty segments or define how trailing slashes should be handled.

Comparisons

ApproachBest forExample
array[array.length - 1]Directly reading the last itemitems[items.length - 1]
array.at(-1)Modern, readable access from the enditems.at(-1)
array.slice(-1)[0]Creating a one-item slice, though less directitems.slice(-1)[0]
if/elseMultiple statements or highly explicit logicif (last === "index.html") { ... }
Ternary ? :A short two-way value selectionlast === "index.html" ? a : b
href.split("/")Simple strings when URL structure is controlledhref.split("/")
new URL().pathnameBrowser URL parsing that ignores query strings and hashesnew URL(location.href).pathname

Array.prototype.at() is especially readable for end-relative access:

const items = ["guides", "arrays", "index.html"];

console.log(items.at(-1)); // "index.html"
console.log(items.at(-2)); // "arrays"
console.log(items.at(-3)); // "guides"

Use at() when the environments you support provide it; use length - n when compatibility with older JavaScript environments is required.

Take Quiz

Cheat Sheet

const items = ["one", "two", "three"];

items.length;             // 3
items[0];                 // "one" — first item
items[items.length - 1];  // "three" — last item
items[items.length - 2];  // "two" — second-to-last item
items[items.length - 3];  // "one" — third-to-last item

items.at(-1);             // "three" — modern alternative
items.at(-2);             // "two"
const last = items[items.length - 1];
const result = last === "index.html"
  ? items[items.length - 3]
  : items[items.length - 2];

Rules to remember:

  • Arrays start at index 0.
  • The final valid index is length - 1.
  • An invalid index returns undefined; it does not throw an error by itself.
  • Check items.length before accessing items far from the end.
  • For URLs, prefer new URL(url).pathname over manually splitting the full href.

FAQ

How do I get the last element of a JavaScript array?

Use array[array.length - 1], or use array.at(-1) in modern JavaScript.

How do I get the second-to-last item in an array?

Use array[array.length - 2] or array.at(-2).

What happens if I access an array index that does not exist?

JavaScript returns undefined. For example, [][0] and ["a"][5] both return undefined.

Should I use == or === when checking for "index.html"?

Use ===. Strict equality avoids automatic type conversion and is the normal choice in JavaScript.

Why does splitting a URL sometimes create an empty final array item?

A trailing slash creates it. For example, "/docs/".split("/") ends with an empty string. Remove empty items with .filter(Boolean) if that matches your intended behavior.

Why is unescape() not recommended?

unescape() is deprecated. For URL-encoded path text, use decodeURIComponent() instead.

How can I ignore query parameters when checking a URL filename?

Use new URL(window.location.href).pathname. The pathname does not include query parameters such as ?page=2 or hash fragments such as #section.

Take Quiz

Mini Project

Description

Build a small breadcrumb-label helper. It reads a URL path, removes empty path segments, and chooses a useful parent label. If the path ends in index.html, it skips that filename and selects the directory before it.

Goal

Create a function that returns the correct parent label for normal pages and index.html pages.

Requirements

Use new URL() to read the path portion of a URL. Remove empty path segments. Return the third-to-last segment when the final segment is index.html. Return the second-to-last segment for other paths. Return null when there are not enough segments.

Take Quiz

Keep learning

Related questions

View more