Introduction and Overview

Welcome to our exploration of TypeScript's loop structures — important constructs for automating repetitive operations. We will be delving into the intricacies of the For Loop, For-In Loop, and For-Of Loop. Let's begin!

Introduction to TypeScript 'For' Loops

Much like replaying your favorite track, loops are employed to execute tasks repetitively. Here's a straightforward for loop that prints numbers from 1 to 5:

Our for loop begins by initializing i as 1, sets the condition i <= 5, and increments i by 1 in each iteration using i++. Consequently, i moves from 1 to 5, wherein each round prints the current value of i.

Note: i++ is an increment operation that augments the value of i by 1. It is essentially equivalent to i = i + 1 or i += 1, but in a more concise format.

Deep Dive into 'For' Loop

Let's revisit our example:

The For Loop consists of three components:

  • Initialization: Here, i begins with a value of 1.
  • Condition: The loop continues as long as i <= 5 holds true.
  • Changes: In this case, i++ advances i by 1 with each succeeding loop iteration.
    • The changes can vary as per the requirements; we could also decrement i by 1 if the scenario warrants.

The generalized structure of the loop remains fixed:

As an example, consider this snippet that lists all seven days of the week:

Exploring 'For-In' Loop

The for-in loop iterates over the properties of an object, almost as though checking the contents of a bag:

In this case, feature sifts through each property of the star object, and star[feature] retrieves the value for each attribute.

Discovering 'For-Of' Loop

The for-of loop operates on iterable elements like arrays. Consider a list of planets:

In this example, planet traverses each element in planets, printing each planet. Notice that indices aren't required when using for-of as you iterate over the elements themselves.

Lesson Review and Further Practice

Bravo! You've adeptly navigated through TypeScript's for, for-in, and for-of loops. These fundamental pillars will help you write clean and efficient codes.

Next up, we'll fine-tune these skills through practical exercises. Practice is key to cementing and integrating your newfound knowledge. Best of luck!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal