Lesson Overview

Welcome to the world of iterations and loops. Let's dive into TypeScript's while loops! While loops are essential in programming because they allow code to be executed repeatedly while a certain condition remains true. They function similarly to an action that you repeat until a certain condition changes; for instance, cleaning a room until it's no longer messy. The while loop runs as long as the condition is met.

What are While Loops?

while loops in TypeScript are control flow statements that allow a block of code to be executed repeatedly while a given condition remains true. For instance, consider a situation where you keep playing outside while it's sunny. Here's what a while loop in TypeScript might look like:

In this example, we initialize a counter with an initial value of 0. The current counter value is then logged as long as its value is less than 5. Once the value reaches 5 or higher, the loop execution stops.

The Syntax of While Loops

A while loop in TypeScript comprises a condition and a body of code. If the condition is true, the code block (body) within the while statement is executed.

Practical Examples with While Loops

Imagine the need to run a countdown from 5 to 1. This can conveniently be achieved using a while loop as follows:

Compound Conditions with While Loops

while loops in TypeScript can use compound conditions utilizing && (and) or || (or). For example, consider a scenario where you're saving up for a bike and want to stop saving once you hit your goal, or when winter starts, whichever comes first:

Common Pitfalls in Using While Loops

It's crucial to avoid creating an infinite loop in TypeScript, where the condition always remains true, and thereby the loop never ends. In the example below, the increment step is missing, resulting in an infinite loop:

Lesson Summary and Practice

Fantastic! You've now learned to use while loops, understood their syntax, and applied them to real-world scenarios. Now it's time to complete some hands-on exercises to solidify these skills. Brace yourself for a fascinating journey into the TypeScript world! Be prepared: adventures lie ahead!

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