Contenido del Curso
Introduction to TypeScript
Introduction to TypeScript
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:
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.`)
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.
const
is used to declare a constant. A constant is a variable whose value cannot be changed, except by reassignment;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 adds1
to a variable. There is also the decrement operator--
, which subtracts1
from a variable. Yes, it's that simple; there's nothing to fear.
¡Gracias por tus comentarios!