Emmanuel Akinfulubi

JavaScriptArray

Get the first and last element of an array in JavaScript

Beginner · 3 min read

Getting the first or last item of a list comes up all the time: the latest message in a chat, the newest order, the final stop on a route. The first item is easy. The last one has an old, clumsy answer and a newer, clean one, and there is a tempting third option that looks right and quietly isn't.

In this tutorial you will read the first, last and second-to-last item of an array with the at method. Then you will find out what xs[-1] really gives you. You only need to know what an array and an index are.

Indexes start at 0

Each item in an array has a position number, its index. The first item is at index 0, the second at index 1, and so on. So the last item is at index length - 1: an array of four items has indexes 0, 1, 2 and 3.

JavaScript

const stops = ['Yaba', 'Surulere', 'Mushin', 'Oshodi'];
console.log(stops[0]);      // 'Yaba'
console.log(stops.length);  // 4
console.log(stops[3]);      // 'Oshodi'

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

6 First, last and nth

easy

Read the first, last and second-to-last element. Then check what xs[-1] actually gives you.

Stuck? Three hints, smallest first
  1. 1. at(-1) counts back from the end; at(0) is the first.
  2. 2. xs[-1] is not an error and not the last element. Ask yourself what -1 becomes when used as a property key.
  3. 3. Reading out of range gives undefined, so a first/last helper never needs a try/catch.

Step 1: the old way to get the last item

Before at existed, you wrote length - 1 inside the brackets.

Step 1

const stops = ['Yaba', 'Surulere', 'Mushin', 'Oshodi'];
console.log(stops[stops.length - 1]); // 'Oshodi'

It works, but you have to type the array's name twice, and it gets noisy for the second-to-last item: stops[stops.length - 2].

Step 2: the wrong turn, xs[-1]

Some languages let you write xs[-1] for the last item. In JavaScript it looks like it should work. It doesn't, and it doesn't throw an error either:

Step 2

const stops = ['Yaba', 'Surulere', 'Mushin', 'Oshodi'];
console.log(stops[-1]);                  // undefined
console.log(Object.hasOwn(stops, '-1')); // false

An array is a kind of object, and square brackets look up a property by name. JavaScript turns -1 into the text '-1' and looks for a property with that name. There isn't one, so you get undefined. Object.hasOwn(stops, '-1') confirms that no such property exists.

Silent undefined is the dangerous part. Your code keeps running with a missing value and fails somewhere else later.

Step 3: at() counts from either end

at(i) reads the item at index i. A negative index counts back from the end: at(-1) is the last item, at(-2) the one before it.

Step 3

const stops = ['Yaba', 'Surulere', 'Mushin', 'Oshodi'];
console.log(stops.at(0));  // 'Yaba'
console.log(stops.at(-1)); // 'Oshodi'
console.log(stops.at(-2)); // 'Mushin'

Step 4: first and last helpers

Wrap those in two tiny functions so the rest of your code reads clearly.

Step 4

const first = (xs) => xs.at(0);
const last = (xs) => xs.at(-1);
const stops = ['Yaba', 'Surulere', 'Mushin', 'Oshodi'];
console.log(first(stops)); // 'Yaba'
console.log(last(stops));  // 'Oshodi'

Step 5: out of range is undefined, not an error

What if the index is too big, or the array is empty?

Step 5

const stops = ['Yaba', 'Surulere', 'Mushin', 'Oshodi'];
console.log(stops.at(99)); // undefined
console.log([].at(0));     // undefined
console.log([].at(-1));    // undefined

Reading past the end never throws in JavaScript. It gives undefined. That is why first and last need no try/catch. The catch is that you can't tell an empty array apart from an array whose last item really is undefined. If that matters, check xs.length first.

Step 6: strings have at() too

at also works on strings, so the same trick gets the last letter.

Step 6

console.log('Lagos'.at(-1)); // 's'
console.log('Lagos'.at(0));  // 'L'

The full solution

The panel defines first and last, reads from both ends, and prints stops[-1] so you can see the trap. Press Run to see the output and the checks.

The answer

const stops = ['Yaba', 'Surulere', 'Mushin', 'Oshodi'];

const first = (xs) => xs.at(0);
const last = (xs) => xs.at(-1);

console.log('first     :', first(stops));
console.log('last      :', last(stops));
console.log('at(-2)    :', stops.at(-2));
console.log('stops[-1] :', stops[-1], '<- a property named "-1", which does not exist');
console.log('the old way:', stops[stops.length - 1]);
console.log('out of range:', stops.at(99), ' on an empty array:', [].at(0));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('at(0) is the first', first(stops), 'Yaba');
test('at(-1) is the last', last(stops), 'Oshodi');
test('at(-2) is the one before it', stops.at(-2), 'Mushin');
test('xs[-1] is undefined, not the last element', stops[-1], undefined);
test('because there is no property called "-1"', Object.hasOwn(stops, '-1'), false);
test('the length-based form does work', stops[stops.length - 1], 'Oshodi');
test('reading past the end is undefined, not an error', stops.at(99), undefined);
test('and an empty array has no first element', [].at(0), undefined);
test('at() works on strings too', 'Lagos'.at(-1), 's');

at exists because xs[-1] looks like it should work and does not. Bracket access converts its argument to a string key, so xs[-1] asks for a property literally named "-1" — absent, hence undefined. Assigning to it would add that property without changing length, which is the confusing version of the same mistake.

Everything here returns undefined rather than throwing, which is why a last() helper needs no error handling. It is also why an empty array and an array whose last element is undefined are indistinguishable through at alone.

Common mistakes

  • Writing xs[-1]. It reads a property named '-1', which doesn't exist, so you get undefined. Use xs.at(-1).
  • Writing xs[xs.length]. That is one past the end, because indexes start at 0. The last index is length - 1.
  • Assigning to xs[-1]. xs[-1] = 'x' adds a strange property named '-1' and leaves length and the last item unchanged.

Try it yourself

  1. Write secondToLast(xs) with at, and check it on [1, 2, 3] and on [1].
  2. Given an array of messages, print the newest three with slice(-3).
  3. Write lastOr(xs, fallback) that returns fallback when the array is empty.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.