Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
  9. JavaScript: Iterators
    3Topics
    |
    3 Quizzes
Lesson 7, Topic 2
In Progress

JavaScript: For Loop

Yasin Cakal 18 Nov 2021
Lesson Progress
0% Complete

Instead of repeatedly writing the same code, loops allow us to instruct computers to repeat a specific block of code on their own. A for loop is one way to give computers these instructions.

An iterator variable is usually present in all three expressions in a typical for loop. On each loop iteration, the iterator variable is initialized, checked against the stopping condition, and a new value is assigned. Iterator variables can have any name, but it’s best to use one that’s descriptive.

Within the parentheses of a for loop, there are three expressions separated by ; :

  1. The loop is started with an initialization, which can also be used to declare the iterator variable.
  2. The iterator variable is evaluated against a stopping condition: if the condition evaluates to true, the code block will run, and if it evaluates to false, the code will stop.
  3. On each loop, an iteration statement is used to update the iterator variable.

The syntax for the for loop is as follows:

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

The output, in this case, would be as follows:

0
1
2
3
4

Let’s take a closer look at the example:

  1. Let counter = 0 as the initialization, and the loop will begin counting at 0.
  2. The loop will run as long as the iterator variable, counter, is less than 5, which is the stopping condition.
  3. counter++ is the iteration statement. This means that the value of counter will increase by one after each loop. For the first iteration, the counter will be set to 0, for the second iteration, to 1, and so on.
  4. console.log(counter), the code block inside the curly braces, will run until the condition evaluates to false. When counter is greater than or equal to 5, the condition will be false — this point is sometimes referred to as the stop condition.

This for loop allows you to programmatically write 0, 1, 2, 3, and 4.

Responses

Leave a Reply

%d bloggers like this: