Start learning free

LESSON 145 OF 348 · LOOPING OVER ARRAY INDICES

Looping Through Arrays with Indices in TypeScript

Lesson Read the full explanation

In some instances, we will want to loop through an array using indices.

The indices of an array meals are all the integer values from 0 to meals.length - 1, so we can iterate over them using an index variable i:

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 of this code is:

Meal number 1 is pancakes.
Meal number 2 is pasta.
Meal number 3 is pizza.
Meal number 4 is avocado.

Assignment
Now let's print the temperature on each day, in this format:

On day 1 the temperature is 10.

On day 2 the temperature is 60.

...


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    TYPESCRIPT · LOOPING OVER ARRAY INDICES

    Looping Through Arrays With Indices in TypeScript, explained

    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 = 0 starts at the first index and runs once, before the loop.
    • i < meals.length is checked before every pass. With four elements, the loop runs while i is 0, 1, 2 and 3, and stops when it reaches 4.
    • i++ adds 1 to i after each pass.
    • Inside the body, meals[i] is the element at the current index, and i + 1 turns 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 from let i = 0, so no annotation is needed. An annotation such as temperatures: number[] on the array describes the elements, and the compiler uses it to check what you do with temperatures[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. Reading meals[10] in a four-element array yields undefined. The compiler, with the settings used in these lessons, still thinks the value has the element type, so it won't warn you.
    • for...of is 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 <= with length. The last valid index is length - 1, so i <= temperatures.length runs one pass too many. That extra pass prints On 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 i where a human number is wanted. The index 0 is "day 1" for a reader, so the text uses i + 1, while the lookup uses i.
    • Forgetting i++. The counter never changes, the condition stays true, and the loop never ends.
    • Confusing i and temperatures[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.

    1. Write the loop header. Start i at 0 and continue while i < temperatures.length, adding 1 with i++. The strict < matters because temperatures.length is not a valid index.
    2. 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 0 to length - 1.
    • The loop for (let i = 0; i < arr.length; i++) visits every index once, in order.
    • Use arr[i] for the element and i + 1 when you want counting from 1.
    • A condition with <= instead of < goes one step past the end and reads undefined.
    • Template literals with ${...} build the output sentences.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free