Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you think you have some skills to help others

help someone and become a part of our community - List Q & A

TypeScript - for loop / foreach loop

0 contributions
3 points

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
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more