Contenido del Curso
Introduction to TypeScript
Introduction to TypeScript
While-Loop
Now, we've moved on to loops, and it's time to quickly learn how to work with large amounts of data. Loops help to repeat a specific action until a certain condition is met, which will stop the loop.
At the beginning of each loop iteration, the condition is checked, and if it evaluates to true
, the loop will execute once, and the condition will be checked again until it returns false
. When the condition evaluates to false
, the loop will stop.
Theory is good, but let's move on to practice. Introducing the while
loop. This loop will perform a specific action as long as the condition remains true
. It's the simplest and the first of all loops. The parent of all other loops and my good friend. Syntax:
The syntax is very simple and easy to remember, but it's best remembered through practice. Let's look at a practical example of using the while
loop, where we will create a new variable of type boolean
, and it will be our condition:
let condition: boolean = true; let number_of_rabbits: number = 2; while (condition) { number_of_rabbits = number_of_rabbits * 2; if (number_of_rabbits > 50) { condition = false; } } console.log(`Total number of rabbits is ${number_of_rabbits}`)
Using a loop, we multiplied the number of rabbits considering that every 2
rabbits would produce offspring of two new rabbits. However, we had a condition that there should not be more than 50
rabbits.
But why did we end up with 64
rabbits? We won't be able to feed such a large number of rabbits!
The GIF below explains why this happens.
Let's edit the code so that the extra rabbits go to another farm. What happens to them on the other farm should not concern us.
let condition: boolean = true; let number_of_rabbits: number = 2; while (condition) { number_of_rabbits = number_of_rabbits * 2; if (number_of_rabbits > 50) { condition = false; } } console.log(`Total number of rabbits is ${number_of_rabbits}`) console.log(`Extra rabbits: ${number_of_rabbits - 50}`)
Now we see how many rabbits we are sending to another farm. We don't care that they are raising crocodiles on the other farm.
We can also remove the condition from the loop by incorporating it into the condition's body. This way, we will use fewer lines of code and improve the code overall.
let number_of_rabbits = 2; while (number_of_rabbits < 50) { number_of_rabbits = number_of_rabbits * 2; } console.log(`Total number of rabbits is ${number_of_rabbits}`) console.log(`Extra rabbits: ${number_of_rabbits - 50}`)
¡Gracias por tus comentarios!