본문으로 건너뛰기

While Loops

While Loops

In real life, we often repeat something until a certain condition is met.

For example, "Wait until the water boils and then turn off the heat."

A while loop in programming repeatedly executes a block of code as long as a given condition remains true (true).


Syntax

while (condition) {
// Code to be executed as long as the condition is true
}

Example 1: Counting Numbers

Let's look at an example of counting down from 5 to 1.

let number = 5;

while (number > 0) {
console.log(number);
number--;
}

In this example, console.log(number); is executed as long as number is greater than 1, and then number is decreased by 1.


Example 2: Eating Snacks Until the Money Runs Out

Imagine you have 1000 won and you keep buying 200 won snacks until you have less than 200 won left.

let money = 1000;

while (money >= 200) {
console.log('Bought a snack!');
money -= 200;
}

console.log(`You have ${money} won left.`);

Caution: Infinite Loops

The most important thing to watch out for when using a while loop is to avoid an infinite loop.

An infinite loop is a situation where the condition is always true, so the loop never stops.

Such infinite loops can cause a program to stop responding or use excessive system resources.

For example, the following code results in an infinite loop:

let number = 5;

while (number > 0) {
console.log(number);
// The value of number does not decrease, so the condition is always true!
}

To avoid an infinite loop, always review and test your code to ensure that the condition can eventually become false. This principle is important not just for while loops but for all types of loops.

다음 내용이 궁금하다면?

월 12,500원 PLUS 멤버십 가입 or 강의를 등록해 주세요!