Trusted answers to developer questions

How to execute a for-loop in JavaScript

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

A for-loop is a control flow statement which is used to execute a block of code a number of times. The flow of the for-loop is specified after each execution of the code block (called an iteration).

Imagine a situation where you have to do a certain task a hundred times. How would you do that? You could type the command to achieve the task a hundred times, or maybe copy-paste it repeatedly.

Of course, that would be quite tedious. This is where loops come into use. When using a for-loop, those hundred lines of code can be written in as few as three to four statements.

for-loop
for-loop

Syntax

This is what a for-loop looks like in JavaScript:

/* for-loop syntax in JavaScript */
for (variable_initialize; condition; change_variable) {
// code block to be executed
}

Arguments

  • variable_initialize (optional): This statement is executed once before the execution of the for-loop code block. This is used to define the counter variable etc. you might be using to control the flow.

  • condition: This statement defines the condition on which the control flow (each iteration) of the for-loop depends.

  • change_variable: This statement is executed after each iteration of the for-loop. This can be used to update the initialized control variable.

Note: variable_initialize is optional since you can use an already initialized variable instead. Do not forget the ; following the variable_initialize even if you decide to skip it!


Flow Diagram

svg viewer

Examples

This code will print out the incremented temp variable from 0 through 4, with an updated value in each iteration, followed by the word : Educative!. The expanded version for the same code is also given in the second code tab, which should be helpful in understanding how exactly the for-loop executes.

for (var temp = 0; temp < 5; temp++) {
// Runs 5 times, with values of temp 0 through 4.
console.log(temp + ": Educative!");
}

RELATED TAGS

javascript
forloops
method
control structures
iteration
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?