for Loop

for Loop

  • The for loop consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.

  • The three expression help determine how many times the loop will iterate before it terminates

  • The statements involve an iterator variable (usually depicted as an “i”)

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}
  • statement 1 is executed (one time) before the execution of the code block

  • statement 2 defines the condition for executing the code block

  • statement 3 is executed (every time) after the code block has been executed

Example

for (let i = 0; i < 5; i++) {
  console.log(`${i} fish`)
}

JS Bin on jsbin.com

Exercise

Write a program that uses a for loop to print (using console.log()) a countdown from 10 to 1

JS Bin on jsbin.com