Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Do-While Loop | Loops
Introduction to TypeScript
course content

Conteúdo do Curso

Introduction to TypeScript

Introduction to TypeScript

1. TypeScript Fundamentals
2. Conditional Statements
3. Arrays
4. Loops
5. Functions

book
Do-While Loop

There are situations when we need to perform an action in the loop at least once before checking the condition.

Let's say you need to charge a user for subscribing to your paid service. You need to deduct the money at least once and then check for how many months the user has subscribed. This is where a do-while loop can help you, for example:

12345678910
let number_of_months: number = 3; let money: number = 920; const price: number = 105; let number_of_charges = 0; do { money = money - price; number_of_charges++; } while (number_of_months != number_of_charges) console.log(`You have ${money} left after subscribing to our service.`)
copy

Let's go through the code above and find out what each line means.

  • number_of_months is the number of months the user subscribes to our service;
  • money is the amount of money in the user's account;
  • price is the price for one month of subscription;
  • number_of_charges is the variable we will count using our loop. It represents the number of charges from the user's account.

In the loop, we deduct money from the user's account at least once, and then we check the condition number_of_months > number_of_charges.

So, we can draw some conclusions:

  • do-while first performs the action and then checks the condition;
  • while first checks the condition and then performs the action.

You may have also noticed some new syntax in the code above. Let's quickly go over what it is.

  1. const is used to declare a constant. A constant is a variable whose value cannot be changed, except by reassignment;
  2. number_of_charges++ -- ++ is the increment operator. In simple terms, number_of_charges++ does the same as
    number_of_charges = number_of_changes + 1;. Increment adds 1 to a variable. There is also the decrement operator --, which subtracts 1 from a variable. Yes, it's that simple; there's nothing to fear.
What is the difference between `while` and `do-while` loops?

What is the difference between while and do-while loops?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 4. Capítulo 3
We're sorry to hear that something went wrong. What happened?
some-alt