Software Imagineer's blog

Ways to iterate an array in TypeScript

Wed Jul 26 2017

Quick overview of ways to iterate an array in TypeScript.

For loop

Probably the cleanest way to write a loop. Loop index variable, condition and increment are all defined in the loop head. This leaves loop body clear.

    var x = [7, 8, 4, 3];
    for(var a=0; a<x.length; a++){
        console.log(x[a]);
    }

While loop

Slightly messier that For loop since loop index is declared outside of the loop head and you have to remember to increment loop index after executing the loop body.

    var x = [7, 8, 4, 3];
    var a = 0;
    while(a < x.length){
        console.log(x[a]);
        a++;
    }

Do While loop

Very much like while loop, but executes loop body before evaluating loop condition.

    var x = [7, 8, 4, 3];
    var a = 0;
    do{
        console.log(x[a]);
        a++;
    }
    while(a < x.length);

ForIn loop (Do not use this for arrays)

ForIn loop iterates over keys of an object. You might run into strange behaviour using ForIn loop for arrays, because array keys might be out of order or include internal variables depending on JS engine you are running on. Moreover, variable "a" will be of string type.

    var x = [7, 8, 4, 3];
    for(var a in x){
        console.log(x[a]);
    }

ForOf loop

ForOf loop iterates over iterable collections (Array, Map, Set, String, TypedArray, arguments and objects which implement iterable protocol). ForOf loop has been introduced in ES6, so be aware that not all browsers may support it.

    var x = [7, 8, 4, 3];
    for(let a of x){
        console.log(a);
    }

Stay tuned for next post where we will go through functional style of loop iteration in TypeScript/JavaScript.