TIL21 - JS - Loops

Peter D Lee·2020년 8월 30일
0

JavaScript

목록 보기
10/19

1. For Loop

Syntax

for (initializer; stopping condition; iterator) {
  code block;
}
  • the for loop statement is comprised of three expressions - initializer, stopping condition, and iteration statement
  • initializer 'initializes' the for loop and can declare the iterator variable
  • stopping condition is the conditional statement that defines the condition under which the for loop will keep going - as long as this stopping condition is true, the code block inside {} of the for loop will continue to run. When this stopping condition evaluates to false, the loop stops.
  • iteration statement updates the iterator variable on each loop

> ex)

for (let i = 0; i < 5; i++) {
  console.log(i);
}
/* Prints:
0
1
2
3
4
*/

2. While Loop

Syntax

let variableName;
while (stopping condition) {
  code block;
  iteration statment;
}
  • Typically, you use would for loop if you know how many times you would run the loop, and use while loop if you don't know in advance how many times a loop should run

3. Do.. While Statement

If you need to have a block of code run at least once regardless of any conditions, but after running once, you want it to run only when some conditions are met, you can use the do..while statement instead of the while loop

Syntax

let variableName;
do {
  code block;
  iteration statement;
} while (stopping condition);

4. Break

If you want a loop to stop before the pre-set stopping condition renders false if another special condition is met, you can do so using the break keyword

Syntax

for (initializer; stopping keyword; iteration statement) {
  if (break condition) {
    break;
  }
  code block;
}

or

for (initializer; stopping keyword; iteration statement) {
  code block;
  if (break condition) {
    break;
  }
}

0개의 댓글