Mastering Loops with TypeScript

Introduction

Greetings, Explorer! In this lesson, we will delve into the essential tools of programming loops. Loops simplify and enhance the efficiency of repetitive tasks — much like a coffee maker brewing multiple cups with a single press, they automate processes to ensure consistent outcomes. We will explore the universe of looping using TypeScript and gain hands-on experience by applying loops to arrays and strings.

Understanding Looping

Imagine listening to your favorite song on repeat. That's the concept of loops in programming. For instance, we can use a for loop to print greetings for a group of friends.

let friends: string[] = ["Alice", "Bob", "Charlie", "Daniel"];

for (let i: number = 0; i < friends.length; i++) {
    // `i` is the index that changes with each iteration
    // For each friend, print the greeting
    console.log(`Hello, ${friends[i]}! Nice to meet you.`);
}

// Output:
// Hello, Alice! Nice to meet you.
// Hello, Bob! Nice to meet you.
// Hello, Charlie! Nice to meet you.
// Hello, Daniel! Nice to meet you.

Loops allow us to execute repetitive sequences automatically and efficiently.

For Loop in TypeScript

The for loop is a control flow statement that allows code to be executed repeatedly.

The structure of a for loop is typically for (initialization; condition; iteration) { loop body }. In TypeScript, type annotations ensure that variables are used correctly, enhancing our programming experience.

  1. Initialization: This sets up the loop variable and includes type annotations. It's executed once when the loop begins.
  2. Condition: A Boolean expression determines if the loop will continue or stop. If true, the loop continues; if false, it ends, and the flow jumps to the next statement after the loop block.
  3. Iteration: This updates the loop variable. This executes after the loop body and right before the next condition check.
  4. Loop Body: The block of code that executes in each loop.

Let's print a range of numbers using a for loop:

for (let num: number = 0; num < 5; num++) {
    console.log(num);
}

// Output:
// 0
// 1
// 2
// 3
// 4

In each cycle, the variable num is updated after executing the code inside the block.

Enhanced For Loop in TypeScript: "for...of"

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