For loops in Typescript/Javascript and Angular

Coming from a C/Java/C# background I always struggle with the for / foreach loop in Typescript (or Javascript).  Today, I thought I would blog about it, to help other programmers with a similar background and to help myself remember.  Since the syntax is the same for Typescript or Javascript I will just refer to both languages as Typescript for the rest of this blog.

In my most recent background experience, prior to moving to Angular/Typescript, which was C#, there is a for loop and a foreach loop.  In Angular/Ionic you have a *ngFor, for and foreach.  Each of these has their own uses and syntax, with the for loop being pretty much identical to C# version.

Typically in C# these loops are as follows:

for (int index = 0; index < maxCount; index++) { loop stuff happens here with index. }

foreach (object tmpObject in listOfObjects) { loop stuff happens here with tmpObject. }

for loop - Typescript

In Typescript the for loop has a similar syntax to C#.

for(var index=0; index < maxCount; index++)  OR for(let index=0; index < maxCount; index++)

However Typescript has two other variants of the for loop:

for(var item in itemList){}

for(var item of itemList){}

for in will iterate over itemList returning the index of each item in the list.

for of will iterate over itemList returning each item in the list.  Very much like C# foreach loop.

foreach loop - Typescript

The foreach loop varies in syntax.  In C# the syntax is:

foreach (Type variable in collection) { }


where foreach and in are keywords.  Type is the type of one item in the collection to be iterated.  collection is the list values/objects to iterate.

In Typescript the syntax is radically different:

collection.forEach((item, index, array) => { loop stuff }); OR

collection.forEach(loopFunction, thisObject); where loopFunction has parameters item, index, array and this gets the context of thisObject.  To better understand 'this' in context of thisObject, review and run the github project.

item is the current element from the collection that is being processed.

index is the current position from the collection that is being processed. This is optional.

array is a copy of the collection that is being processed. This is optional.

thisObject is anything and every iteration of the loop gets the same value into ‘this’

for loop - Angular (*ngFor)

 The *ngFor loop has a syntax somewhat like the C# foreach loop, but is only used in the html element code:

*ngFor=”let curObject of listOfObjects”

*ngFor, let, of are keywords.

curObject is the current item in the list being iterated.

listOfObjects is the list of items to iterate over.

 

There is  a github project with examples in ZimBaroo's Geeks Repository

 

Add comment