Languages
[Edit]
EN

TypeScript - for loop / foreach loop

3 points
Created by:
Kate_C
2857

In TypeScript there are few ways to use for loop.

1. Classic for loop over string example

// ONLINE-RUNNER:browser;

let text = 'Text...';

for(let i = 0; i < text.length; ++i)
    console.log(text[i]);

Output:

T
e
x
t
.
.
.

2. Foreach loop (for...of loop) over array example

// ONLINE-RUNNER:browser;

let array = [ 1, 2, 3, 'text' ];

for(let entry of array)
    console.log(entry);

Output:

1
2
3
text

3. for...in loop over object example

// ONLINE-RUNNER:browser;

let object = {
    'key1' : {
        name : 'John',
        age : 43
    },
    'key2' : {
        name : 'Kate',
        age : 54
    },
    'key3' : {
        name : 'Diego',
        age : 21
    },
};

for(let key in object) {
    let entry = object[key];

    console.log(key + ' : ' + entry.name + ', ' + entry.age);
}

Output:

key3 : Diego, 21
key1 : John, 43
key2 : Kate, 54

Note: for...in loop only iterates over enumerable and non-Symbol properties.

References:

  1. Classic for loop - MDN Docs
  2. for...in loop - MDN Docs
  3. for...of loop - MDN Docs
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.