for statement | MDN

Wonkook Lee·2021년 7월 29일
0

Docs

목록 보기
1/1
post-thumbnail

The for Statement

다시 한 번 살펴보는 for문

(1) Syntax

for ([initialization]; [condition]; [final-expression]) statement

initialization

An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. The result of this expression is discarded.

condition

An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is excuted.

final-expression

An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.

statement

A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a block statement ({ ... }) to group those statements. To execute no statement within the loop, use an empty statement (;).


(2) Optional for expressions

All three expressions in the head of the for loop are optional.

For example, in the initialization block is not required to initialize variables:

let i = 0;
for (; i < 9; i++) {
  console.log(i)
  // more statements
}

(3) break

Like the initialization block, the condition block is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.

for (let i = 0;; i++) {
  console.log(i);
  if (i > 3) break;
  // more statements
}

You can also omit all three blocks. Again, make sure to use a break statement to end the loop and also modify(increase) a variable, so that the condition for the break statement is true at some point.

let i = 0;
for (;;) {
  if (i > 3) break;
  console.log(i);
  i++;
}

(4) continue

The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.

Syntax

continue [label];

label
Identifier associated with the label of the statement.

Description

In contrast to the break statement, continue does not terminate the execution of the loop entirely:
Instead,

  • In a while loop, it jumps back to the condition.
  • In a for loop, it jumps to the update expression.

The continue statement can include an optional label that allows the program to jump to the next iteration of a labeled loop statement instead of the current loop. In this case, the continue statement needs to be nested within this labeled statement.



👋

Source:
for - JavaScript | MDN

profile
© 가치 지향 프론트엔드 개발자

0개의 댓글