What looping with indices means
An array stores its elements in order, and each one has a position called an index. Indices start at 0, so an array with four elements has the indices 0, 1, 2 and 3. In general, the valid indices of an array meals are all the integers from 0 to meals.length - 1.
A loop that counts through those integers lets you reach every element by position, with meals[i]. You use this style when the position matters as well as the value: printing a number next to each element, comparing an element with its neighbour, returning the index of a match, or changing elements in place.
The syntax
The loop is a standard for statement with three parts: where the counter starts, when to continue, and how to advance.
let meals = ["pancakes", "pasta", "pizza", "avocado"];
for (let i = 0; i < meals.length; i++) {
console.log(`Meal number ${i + 1} is ${meals[i]}.`);
}
The output is:
Meal number 1 is pancakes.
Meal number 2 is pasta.
Meal number 3 is pizza.
Meal number 4 is avocado.
let i = 0starts at the first index and runs once, before the loop.i < meals.lengthis checked before every pass. With four elements, the loop runs whileiis 0, 1, 2 and 3, and stops when it reaches 4.i++adds 1 toiafter each pass.- Inside the body,
meals[i]is the element at the current index, andi + 1turns the zero-based index into a human-friendly number that starts at 1.
The string in console.log is a template literal: it is written with backticks, and each ${...} inserts the value of the expression inside the braces. Any expression works there, which is why ${i + 1} prints the arithmetic result.
TypeScript details
- The type of the index is
number. TypeScript infers it fromlet i = 0, so no annotation is needed. An annotation such astemperatures: number[]on the array describes the elements, and the compiler uses it to check what you do withtemperatures[i]. - Annotations do not exist at run time. The compiled JavaScript has no
: number[]. Nothing is checked or converted while the program runs. - Going out of range gives
undefined, not an error. Readingmeals[10]in a four-element array yieldsundefined. The compiler, with the settings used in these lessons, still thinks the value has the element type, so it won't warn you. for...ofis the alternative.for (const meal of meals)gives you the elements without an index. It's simpler when you don't need positions. Use the index loop when you do.
Common mistakes
- Using
<=withlength. The last valid index islength - 1, soi <= temperatures.lengthruns one pass too many. That extra pass printsOn day 5 the temperature is undefined.for a four-element array. - Starting at 1. It skips the first element, which sits at index 0.
- Printing
iwhere a human number is wanted. The index 0 is "day 1" for a reader, so the text usesi + 1, while the lookup usesi. - Forgetting
i++. The counter never changes, the condition stays true, and the loop never ends. - Confusing
iandtemperatures[i]. The first is the position and the second is the value stored there.
The exercise
The lesson gives an array temperatures and asks you to print the temperature of each day in the format On day 1 the temperature is 10., using an index i.
- Write the loop header. Start
iat 0 and continue whilei < temperatures.length, adding 1 withi++. The strict<matters becausetemperatures.lengthis not a valid index. - Print inside the loop. A template literal puts the day number,
i + 1, and the temperature,temperatures[i], into the required sentence.
const temperatures: number[] = [10, 60, -5, 32];
for (let i = 0; i < temperatures.length; i++) {
console.log(`On day ${i + 1} the temperature is ${temperatures[i]}.`);
}
For the four temperatures given, the program prints:
On day 1 the temperature is 10.
On day 2 the temperature is 60.
On day 3 the temperature is -5.
On day 4 the temperature is 32.
The negative temperature needs no special handling. It is a value stored in the array, and the loop only uses non-negative numbers as indices.
Key takeaways
- The valid indices of an array run from
0tolength - 1. - The loop
for (let i = 0; i < arr.length; i++)visits every index once, in order. - Use
arr[i]for the element andi + 1when you want counting from 1. - A condition with
<=instead of<goes one step past the end and readsundefined. - Template literals with
${...}build the output sentences.