Languages
[Edit]
EN

TypeScript - for loop / foreach loop

3 points
Created by:
Bess
571

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

TypeScript

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join