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.
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 - ]
: locArray[locArray. - ];
.(selectedItem);
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:
locArraycontains 6 items, solocArray.lengthis6.locArray.length - 1is5, solastItembecomeslocArray[5], which is"index.html".- The condition is true.
locArray.length - 3is3.
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.
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 = (segments);
(label !== ) {
.().(
.((label))
);
}
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
Comparisons
| Approach | Best for | Example |
|---|---|---|
array[array.length - 1] | Directly reading the last item | items[items.length - 1] |
array.at(-1) | Modern, readable access from the end | items.at(-1) |
array.slice(-1)[0] | Creating a one-item slice, though less direct | items.slice(-1)[0] |
if/else | Multiple statements or highly explicit logic | if (last === "index.html") { ... } |
Ternary ? : | A short two-way value selection |
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 ; it does not throw an error by itself.
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?
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.
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.