Conteúdo do Curso
Introduction to TypeScript
Introduction to TypeScript
`break` keyword
How to quickly stop a loop execution?
Did you know that the lead developer of artificial intelligence always carries a backpack with a red button inside it, which can instantly erase all data from the ChatGPT database? This is done to prevent a scenario where artificial intelligence takes over the world.
Well, in TypeScript, there is a similar function. You can abruptly terminate the execution of a loop using the break
keyword. This can help avoid an infinite loop when there is no clear termination condition defined or when the condition is always true
. For example:
let amount_of_stolen_money = 0; while (true) { amount_of_stolen_money = amount_of_stolen_money + 1000; console.log(`The amount of stolen money: ${amount_of_stolen_money}`); if (amount_of_stolen_money >= 5000) { break; } }
As you can see, there's an eternal true
condition in the code. This means our loop will keep stealing money indefinitely. This is called an infinite loop, and for heaven's sake, avoid infinite loops by all means possible. In the code above, we've set a condition that if the amount of stolen money is greater than or equal to 5000
, we stop the loop. I don't know why we allowed 5,000 hypothetical units to be stolen from us, but it's a good thing we stopped the loop in time.
We can stop the execution of a loop even without a condition, but I can't find a reason why we would want to do that. But such an option exists.
while (true) { console.log("What was I created for?.."); break; }
After just one iteration, the loop terminated its execution.
Obrigado pelo seu feedback!