Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
`break` keyword | Loops
Introduction to TypeScript
course content

Зміст курсу

Introduction to TypeScript

Introduction to TypeScript

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

book`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:

12345678
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; } }
copy

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.

1234
while (true) { console.log("What was I created for?.."); break; }
copy

After just one iteration, the loop terminated its execution.

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 2
We're sorry to hear that something went wrong. What happened?
some-alt