The Wayback Machine - https://web.archive.org/web/20240910214140/https://www.geeksforgeeks.org/javascript-for-loop/
Open In App

JavaScript For Loop

Last Updated : 30 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JavaScript for loop is a control flow statement that allows code to be executed repeatedly based on a condition. It consists of three parts: initialization, condition, and increment/decrement. This loop iterates over a code block until the specified condition is false.

For Loop in JavaScript

A for loop in JavaScript repeatedly executes a block of code as long as a specified condition is true. It includes initialization, condition checking, and iteration steps, making it efficient for controlled, repetitive tasks.

Syntax:

for (statement 1 ; statement 2 ; statement 3){
    code here...
}
  • Statement 1: It is the initialization of the counter. It is executed once before the execution of the code block.
  • Statement 2: It defines the testing condition for executing the code block
  • Statement 3: It is the increment or decrement of the counter & executed (every time) after the code block has been executed.

Example:

javascript
// JavaScript program to illustrate for loop
let x;

// for loop begins when x=2
// and runs till x <=4
for (x = 2; x <= 4; x++) {
    console.log("Value of x:" + x);
}

Output:

Value of x:2
Value of x:3
Value of x:4

Flow chart

This flowchart shows the working of the for loop in JavaScript. You can see the control flow in the For loop.

for loop flow chart

Statement 1: Initializing Counter Variable

Statement 1 is used to initialize the counter variable. A counter variable is used to keep track of the number of iterations in the loop. You can initialize multiple counter variables in statement 1.

We can initialize the counter variable externally rather than in statement 1. This shows us clearly that statement 1 is optional. We can leave the portion empty with a semicolon. 

Example:

javascript
let x = 2;

for (; x <= 4; x++) {
    console.log("Value of x:" + x);
}

Output

Value of x:2
Value of x:3 
Value of x:4

Statement 2: Testing Condition

This statement checks the boolean value of the testing condition. If the testing condition is true, the for loop will execute further, otherwise loop will end and the code outside the loop will be executed. It is executed every time the for loop runs before the loop enters its body.

This is also an optional statement and Javascript treats it as true if left blank. If this statement is omitted, the loop runs indefinitely if the loop control isn’t broken using the break statement. It is explained below in the example.

Example:

JavaScript
let x = 2;
for (; ; x++) {
    console.log("Value of x:" + x);
    break;
}

Output:

Value of x:2

Statement 3: Updating Counter Variable

It is a controlled statement that controls the increment/decrement of the counter variable.

It is also optional by nature and can be done inside the loop body.

Example:

JavaScript
const subjects = ["Maths", "Science", "Polity", "History"];
let i = 0;
let len = subjects.length;
let gfg = "";
for (; i < len;) {
    gfg += subjects[i];
    //can be increased inside loop
    i++;
}
console.log(gfg)

Output

MathsSciencePolityHistory

More Loops in JavaScript

JavaScript has different kinds of loops in Java. Some of the loops are:

LoopDescription
for loopA loop that repeats a block of code a specific number of times based on a conditional expression.
while loopA loop that repeats a block of code as long as a specified condition is true.
do-while loopA loop that executes a block of code at least once, then repeats the block as long as a specified condition is true.
for…of loopIterates over the values of an iterable object (like arrays, strings, maps, sets, etc.)
for…in loopIterates over the enumerable properties of an object (including inherited properties).

Learn and master JavaScript with Practice Questions. JavaScript Exercises provides many JavaScript Exercise questions to practice and test your JavaScript skills.

JavaScript For Loop – FAQs

What is a for loop in JavaScript?

A for loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. It is often used when the number of iterations is known beforehand.

What is the basic syntax of a for loop?

The basic syntax of a for loop consists of three parts: initialization, condition, and increment/decrement.

Example: for (initialization; condition; increment/decrement) { // code to be executed }

How does the initialization part work?

The initialization part is executed only once before the loop starts. It is typically used to initialize a counter variable.

Example: for (let i = 0; i < 5; i++) { console.log(i); } Here, let i = 0 is the initialization.

What is the purpose of the condition part?

The condition part is evaluated before each iteration of the loop. If the condition evaluates to true, the loop body is executed. If it evaluates to false, the loop terminates.

Example: for (let i = 0; i < 5; i++) { console.log(i); } Here, i < 5 is the condition.

How does the increment/decrement part work?

The increment/decrement part is executed after each iteration of the loop. It is typically used to update the loop counter variable.



Previous Article
Next Article

Similar Reads

How to loop through HTML elements without using forEach() loop in JavaScript ?
In this article, we will learn how to loop through HTML elements without using the forEach() method. This can be done in the following ways: Table of Content Approach 1: Using the for loopApproach 2: Using the While loopApproach 3: Using the 'for.....of' statementApproach 4: Using the for...in statementApproach 1: Using the for loopThe HTML element
4 min read
How to Loop Through an Array using a foreach Loop in PHP?
Given an array (indexed or associative), the task is to loop through the array using foreach loop. The foreach loop iterates through each array element and performs the operations. PHP foreach LoopThe foreach loop iterates over each key/value pair in an array. This loop is mainly useful for iterating through associative arrays where you need both t
2 min read
How to Change Values in an Array when Doing foreach Loop in JavaScript ?
The forEach loop in JavaScript is one of the several ways to iterate through an array. ForEach method is different from all other looping methods as it passes a callback function for each element in the array. So, the possible approach to change the values in the array when doing foreach method in JavaScript, the method will not directly change the
3 min read
How to break nested for loop using JavaScript?
The break statement, which is used to exit a loop early. A label can be used with a break to control the flow more precisely. A label is simply an identifier followed by a colon(:) that is applied to a statement or a block of code. Note: there should not be any other statement in between a label name and associated loop. Example-1: Break from neste
3 min read
How to trigger setInterval loop immediately using JavaScript ?
This article will show some simple ways in which the setInterval() method can be made to execute the function without delay. There are many procedures to do so, below all the procedures are described with the example. Note: In this article setInterval() method will start immediately for the 1st time run. Below examples illustrate the above approach
2 min read
How to ignore loop in else condition using JavaScript ?
In this article, we will see the methods to ignore the loop in the else conditions using JavaScript. There are two ways to ignore the loop in the else condition: ContinueBreak Please see this, for explanations of the same. In simple terms, The Break statement exits out of the loop while the continue statement exits out of the particular iteration.
2 min read
What are the microtask and macrotask within an event loop in JavaScript ?
Event Loop: An Event Loop in JavaScript is said to be a constantly running process that keeps a tab on the call stack. Its main function is to check whether the call stack is empty or not. If the call stack turns out to be empty, the event loop proceeds to execute all the callbacks waiting in the task queue. Inside the task queue, the tasks are bro
4 min read
JavaScript SyntaxError - A declaration in the head of a for-of loop can't have an initializer
This JavaScript exception a declaration in the head of a for-of loop can't have an initializer occurs if the for -of loop contains an initialization expression like |for (var i = 0 of iterable)|. This is not valid initialization in for-of loops. Message: SyntaxError: for-of loop head declarations cannot have an initializer (Edge) SyntaxError: a dec
1 min read
How to Pause and Play a Loop in JavaScript using Event Listeners ?
Given below is a JavaScript program for DOM manipulation which is basically about How to Pause and Play a loop in JavaScript using event listeners (not to be confused with delay). In this article, we are using JavaScript with HTML so we need a web browser i.e., Chrome (recommended) or Electron Application. Pausing and playing a loop is such a diffi
4 min read
How to delay a loop in JavaScript using async/await with Promise ?
Given below is a JavaScript code snippet which is basically described how to delay a loop in JavaScript using async/await. In this article, we are using JavaScript either the web browser or Node.js. We all face a difficult situation in delaying a loop in JavaScript unlike C++ where we have sleep() function, but there is nothing like this in JavaScr
2 min read
Disadvantages of using for..in loop in JavaScript
In this article, we will see what are the disadvantages of using for..in loop and how to solve those issues. Disadvantages of using for..in loop: Reason 1: When you add a property in an array or object using the prototype and any other array arr that has no relation with that property when you iterate array x then you get that property. Example: Yo
2 min read
How to loop through a plain object with the objects as members in JavaScript ?
Looping through a plain JavaScript object with objects as members means iterating over each property of the object and accessing its values, which may also be objects. This is a common task in JavaScript, especially when dealing with JSON data or APIs. There are several ways to loop through a plain JavaScript object with objects as members. Here ar
3 min read
JavaScript for...in loop not working - Object property is not defined Error
A for...in loop is a special loop in JavaScript that enumerates all the keys (object property names) of an object. With each new iteration, a new property string is assigned to the loop variable. Error: Uncaught ReferenceError: Object property is not defined If we try to compare this loop variable with a non-string variable a ReferenceError is gene
3 min read
How to iterate an Array using forEach Loop in JavaScript?
Iterating through an array in JavaScript can be done in multiple ways. One of the most common methods is using the traditional for loop. In JavaScript, we have another modern approach to iterate the array which is by using the forEach method. This method is different from the traditional approach as it uses a functional approach. This approach prov
2 min read
How to use async/await with forEach loop in JavaScript ?
Asynchronous is popular nowadays because it gives functionality of allowing multiple tasks to be executed at the same time (simultaneously) which helps to increase the productivity and efficiency of code. Async/await is used to write asynchronous code. In JavaScript, we use the looping technique to traverse the array with the help of forEach loop.
2 min read
Difference between forEach() and map() loop in JavaScript
When we work with an array, it is an essential step to iterate on the array to access elements and perform some kind of functionality on those elements to accomplish any task. For this loops like ForEach() and Map() are used. In this article, we are going to learn the difference between the forEach() and map() loops in JavaScript. JavaScript forEac
3 min read
JavaScript program to print Alphabets from A to Z using Loop
Our task is to print the alphabet from A to Z using loops. In this article, we will mainly focus on the following programs and their logic. Below are the loops used to print Alphabets from A to Z: Table of Content Using for loopUsing the while loopUsing a do-while loop Using for loopThe elements are iterated through a predetermined number of times
4 min read
What is the use of the for...in Loop in JavaScript ?
The for...in loop in JavaScript is used to iterate over the properties (keys) of an object. It allows you to loop through all enumerable properties of an object, including those inherited from its prototype chain. Syntax:for (variable in object) { // code to be executed}Example: Here, the for...in loop iterates over the properties of the person obj
1 min read
What is the use of the Break Statement in a Loop in JavaScript ?
The break statement in JavaScript is used to prematurely terminate a loop, allowing the program to exit the loop before the normal loop condition is met. It is often used to interrupt the loop execution based on certain conditions. Example: Here, the while loop will continue indefinitely (since the condition is true). However, the if statement insi
1 min read
How to Create a While Loop in JavaScript ?
In JavaScript, you can create a while loop using the while keyword followed by a condition. The loop continues to execute as long as the specified condition evaluates to true. Syntax:while (condition) { // Code to be executed while the condition is true // The condition is checked before each iteration}Example: Here, the loop continues to execute a
1 min read
How to Exit a Loop Before it Completes all Iterations in JavaScript ?
In JavaScript, you can exit a loop before it completes all iterations using the break statement. The break statement is used to terminate the loop prematurely based on a certain condition. Example: Here, the loop prints numbers from 1 to 10. However, when i becomes equal to 5, the break statement is executed, causing the loop to terminate immediate
1 min read
How to Push an Object into an Array using For Loop in JavaScript ?
JavaScript allows us to push an object into an array using a for-loop. This process consists of iterating over the sequence of values or indices using the for-loop and using an array manipulation method like push(), to append new elements to the array. We have given an empty array, and we need to push the object into the array. Below is an example
3 min read
Event Loop in JavaScript
In JavaScript, the event loop plays an important role in managing asynchronous operations and ensures the non-blocking behavior of the language. JavaScript is single-threaded, meaning it processes one task at a time and an event loop helps to handle asynchronous tasks efficiently. When an asynchronous operation, like a setTimeout callback or a user
1 min read
What is For...of Loop in JavaScript ?
In JavaScript, the for...of loop is a language construct used to iterate over elements of an iterable object, such as arrays, strings, maps, sets, and other data structures that implement the iterable protocol. It provides a more concise and readable syntax compared to traditional for loops or forEach() methods. Syntax:for (variable of iterable) {
1 min read
How to Write a While Loop in JavaScript ?
In JavaScript, a while loop is a control flow statement that repeatedly executes a block of code as long as a specified condition is true. Syntax:while (condition) { // code block to be executed while condition is true}The loop continues to execute the block of code within its curly braces ({}) as long as the specified condition evaluates to true.
1 min read
What is the fastest way to loop through an array in JavaScript ?
The fastest way to loop through an array in JavaScript depends upon the usecases and requirements. JavaScript has a large variety of loops available for performing iterations. The following loops along with their syntax are supported by JavaScript. Table of Content for loop while loop .forEach() loopfor...of Loopfor loop A JavaScript for loop compr
3 min read
How to Loop through XML in JavaScript ?
In JavaScript, looping over XML data is important for processing and extracting information from structured XML documents. Below is a list of methods utilized to loop through XML. Table of Content Using for loop with DOMParser and getElementsByTagNameUsing Array.from with DOMParser and childNodesUsing for loop with DOMParser and getElementsByTagNam
2 min read
JavaScript Program to Remove Loop in a Linked List
A linked list is a collection of nodes that contain both a data element and a reference (or pointer) to the next node in the collection. A common concern with linked lists is having loops and cycles. When one of the nodes in the linked list points towards any of its previous nodes leading to an infinite cycle. While traversing the list, this can ca
7 min read
How to add a delay in a JavaScript loop?
JavaScript doesn't offer any wait command to add a delay to the loops but we can do so using setTimeout method. This method executes a function, after waiting a specified number of milliseconds. Below given example illustrates how to add a delay to various loops: For loop:[GFGTABS] JavaScript for (let i=0; i&lt;10; i++) { task(i); } function task(i
3 min read
JavaScript Program to Remove Empty Strings from Array Without Loop
Given an array with values and empty strings, our task is to remove empty strings from an array while keeping a record of the removed elements without using explicit loops. Example: Input: Array = ["hello", "", "world", "", "!", " "]; Output: Cleaned Array: [ 'hello', 'world', '!', ' ' ] Removed Elements: [ '', '' ]Below are the approaches to remov
3 min read