for loop basics

The for loop is used to repeat a block of code a certain number of times:

Here is an example of a for loop. Try it out in the code editor.

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

A for loop starts with for keyword, then three statements in parenthesis separated by semicolons:

for (let i = 0; i < 5; i++)

Initialization, let i = 0, declares a loop variable and sets a value to start with;

The limiting step, i < 5, specifies the condition for the loop to go on, so it's clear when to stop looping;

The increment step, i++ (add 1 to i), specifies how to increase the loop counter.

A curly bracket follows at the end of the header line to indicate the start of loop body. Everything inside curly brackets {...} is the loop body. Code block in loop body are indented 4 spaces for easy reading.

Click run and check results in the console:

0
1
2
3
4

JavaScript Compound Statements Style

JavaScript Code Blocks/ compound statements

JavaScript statements can be grouped together in code blocks, inside curly brackets {...}. The purpose of code blocks is to define statements to be executed together.

Combining statements into blocks is a common practice in JavaScript. The block statement is often called compound statement.

for loop is one place you will find statements grouped together in blocks, we'll see compound statements later in JavaScript functions and conditionals.

General rules for complex (compound) statements:

  • Put the opening bracket at the end of the first line. Use one space before the opening bracket.
  • Put the closing bracket on a new line, without leading spaces.
  • Do not end a complex statement with a semicolon.
  • Always use 4 spaces for indentation of code blocks.

results matching ""

    No results matching ""