length and the Last Item

Grade 7, page 3 of 14. A one-minute read.

Every array knows how many items it has, through its length:

JavaScript
const foods = ["burger", "omelet", "pancakes", "soup"];
console.log(foods.length);

It prints

4

Since indexes start at 0, the last item is always at index length - 1. Or, just like strings, you can use .at(-1):

JavaScript
const foods = ["burger", "omelet", "pancakes", "soup"];

console.log(foods[foods.length - 1]);
console.log(foods.at(-1));
console.log(foods.at(-2));

It prints

soup
soup
pancakes

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning