Hone

Lessons · TypeScript · the first item is item 0

Picking an item by position

arr[i] is the item at position i, counting from 0. Out of range gives undefined, not an error.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

The first row, the selected option, the last message: positions are how you reach into a list, and the zero start is the first thing every beginner trips on.

How to think about it

Index 0 is the first item, length - 1 the last, or arr.at(-1). When a read gives undefined, check the index before checking the data.

Worked example

const xs = [10, 20, 30];
Positions 0, 1, 2.
console.log(xs[1]);
20: index 1 is the second item.
console.log(xs[xs.length - 1], xs.at(-1));
30 30: the last item, the long way and with at.
console.log(xs[5]);
undefined: no error, no value.

Your turn

The first item.

const first = items[];

The trap

An out-of-range read is undefined rather than an error, so a wrong index becomes a silent undefined that fails further down the code.

Practise the first item is item 0 on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.