The Wayback Machine - https://web.archive.org/web/20240927032207/https://www.geeksforgeeks.org/loops-in-javascript/
Open In App

JavaScript Loops

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

JavaScript loops are essential for efficiently handling repetitive tasks. They execute a block of code repeatedly as long as a specified condition remains true. These loops are powerful tools for automating tasks and streamlining your code.

For example, suppose we want to print “Hello World” 5 times. This can be done using JS Loop easily. In Loop, the statement needs to be written only once and the loop will be executed 5 times as shown below:

JavaScript
for (let i = 0; i < 5; i++) {
    console.log("Hello World!");
}

Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

1. JavaScript for Loop

The JS for loop provides a concise way of writing the loop structure. The for loop contains initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. 

Syntax

for (initialization; testing condition; increment/decrement) {
    statement(s)
}

Flowchart

  • Initialization condition: It initializes the variable and mark the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.
  • Test Condition: It is used for testing the exit condition of a for loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
  • Statement execution: Once the condition is evaluated to be true, the statements in the loop body are executed.
  • Increment/ Decrement: It is used for updating the variable for the next iteration.
  • Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle.

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

2. JavaScript while Loop

The JS while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. 

Syntax

while (boolean condition) {
    loop statements...
}

Flowchart

while loop

  • While loop starts with checking the condition. If it is evaluated to be true, then the loop body statements are executed otherwise first statement following the loop is executed. For this reason, it is also called the Entry control loop
  • Once the condition is evaluated to be true, the statements in the loop body are executed. Normally the statements contain an updated value for the variable being processed for the next iteration.
  • When the condition becomes false, the loop terminates which marks the end of its life cycle.

Example

JavaScript
// JavaScript code to use while loop
let val = 1;

while (val < 6) {
    console.log(val); 
    val += 1;
}

Output
1
2
3
4
5

3. JavaScript do-while Loop

The JS do-while loop is similar to the while loop with the only difference is that it checks for the condition after executing the statements, and therefore is an example of an Exit Control Loop. It executes loop content at least once event the condition is false.

Syntax

do {
    Statements...
}
while (condition);

Flowchartdo-while

  • The do-while loop starts with the execution of the statement(s). There is no checking of any condition for the first time.
  • After the execution of the statements and update of the variable value, the condition is checked for a true or false value. If it is evaluated to be true, the next iteration of the loop starts.
  • When the condition becomes false, the loop terminates which marks the end of its life cycle.
  • It is important to note that the do-while loop will execute its statements at least once before any condition is checked and therefore is an example of the exit control loop.

Example

JavaScript
let test = 1;

do {
    console.log(test);
    test++;
} while(test <= 5)

Output
1
2
3
4
5

4. JavaScript for-in Loop

JS for-in loop is used to iterate over the properties of an object. The for-in loop iterates only over those keys of an object which have their enumerable property set to “true”.

Syntax

for(let variable_name in object_name) {
    // Statement
}

Example: This example shows the use of for-in loop.

JavaScript
let myObj = { x: 1, y: 2, z: 3 };
for (let key in myObj) {
    console.log(key, myObj[key]);
}

Output
x 1
y 2
z 3

5. JavaScript for-of Loop

JS for-of loop is used to iterate the iterable objects for example – array, object, set and map. It directly iterate the value of the given iterable object and has more concise syntax than for loop.

Syntax:

for(let variable_name of  object_name) {
    // Statement
}

Example: This example shows the use of for-of loop.

JavaScript
let arr = [1, 2, 3, 4, 5];
for (let value of arr) {
    console.log(value);
}

Output
1
2
3
4
5

6. JavaScript Labeled Statement

JS label keyword does not include a goto keyword. Users can use the continue keyword with the label statement. Furthermore, users can use the break keyword to terminate the loop/block. You can also use the break keyword without defining the label but it terminates only the parent loop/block. To terminate the outer loop from the inner loop using the break keyword, users need to define the label.

Syntax

Label:
    statement (loop or block of code)

Example

JavaScript
let sum = 0, a = 1; 

// Label for outer loop 
outerloop: while (true) { 
    a = 1; 

    // Label for inner loop 
    innerloop: while (a < 3) { 
        sum += a; 
        if (sum > 12) { 

            // Break outer loop from inner loop 
            break outerloop; 
        } 
        console.log("sum = " + sum); 
        a++; 
    } 
}

Output
sum = 1
sum = 3
sum = 4
sum = 6
sum = 7
sum = 9
sum = 10
sum = 12

7. JavaScript Break Statement

JS break statement is used to terminate the execution of the loop or switch statement when the condition is true.

Syntax

break;

Example

JavaScript
for (let i = 1; i < 6; i++) {
    if (i == 4) 
        break;
        
    console.log(i);
}

Output
1
2
3

8. JavaScript Continue Statement

JS continue statement is used to break the iteration of the loop and follow with the next iteration. The break in iteration is possible only when the specified condition going to occur. The major difference between the continue and break statement is that the break statement breaks out of the loop completely while continue is used to break one statement and iterate to the next statement.

Syntax

continue;

Example

JavaScript
for (let i = 0; i < 11; i++) {
    if (i % 2 == 0) 
        continue;
        
    console.log(i);
}

Output
1
3
5
7
9

9. JavaScript Infinite Loop (Loop Error)

One of the most common mistakes while implementing any sort of loop is that it may not ever exit, i.e. the loop runs for infinite times. This happens when the condition fails for some reason. 

Example: This example shows an infinite loop.

JavaScript
// JavaScript program to illustrate infinite loop

// Infinite loop because condition is not false
// condition should have been i>0.
for (let i = 5; i != 0; i -= 2) {
    console.log(i);
}

let x = 5;

// Infinite loop because update statement
// is not provided
while (x == 5) {
    console.log("In the loop");
}

JavaScript Loops – FAQs

What are loops in JavaScript?

Loops are a fundamental concept in programming used to repeat a block of code multiple times. In JavaScript, loops allow you to execute a piece of code repeatedly until a specified condition is met.

What are the different types of loops in JavaScript?

JavaScript provides several types of loops:

  • for loop: Used when the number of iterations is known.
  • while loop: Repeats as long as a specified condition is true.
  • do…while loop: Similar to the while loop, but it executes the block of code once before checking the condition.
  • for…in loop: Used to iterate over the properties of an object.
  • for…of loop: Used to iterate over iterable objects like arrays, strings, maps, etc.

How does a for loop work?

A for loop repeats a block of code a certain number of times. It consists of three parts:

  • Initialization: Initialize the loop counter variable.
  • Condition: The loop runs as long as this condition is true.
  • Increment/Decrement: Modify the loop counter variable.
  • Example: for (let i = 0; i < 5; i++) { console.log(i); }

What is the difference between while and do…while loops?

  • while loop: Checks the condition before executing the block of code.
    Example: let i = 0; while (i < 5) { console.log(i); i++; }
  • do…while loop: Executes the block of code once before checking the condition.
    Example: let i = 0; do { console.log(i); i++; } while (i < 5);

How does the for…in loop work?

The for…in loop iterates over the properties of an object (including inherited properties).

Example: const obj = {a: 1, b: 2, c: 3}; for (let key in obj) { console.log(key, obj[key]); }

How does the for…of loop work?

The for…of loop iterates over the values of an iterable object (like an array).

Example: const arr = [1, 2, 3]; for (let value of arr) { console.log(value); }

What is an infinite loop, and how can it be avoided?

An infinite loop occurs when the loop’s terminating condition is never met, causing the loop to run indefinitely. It can be avoided by ensuring that the loop has a condition that will eventually become false.



Previous Article
Next Article

Similar Reads

JavaScript Course Loops in JavaScript
Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. For example, suppose we want to print “Hello World” 10 times. Example: In this example we will print the same things, again and again, to understand the work of Loops. <script> cons
4 min read
Differences Between the for...in & for...of loops in JavaScript
In JavaScript, both for...in and for...of loops are used for iteration, but they have different purposes and behaviors: for...in Loop:The for...in loop iterates over the enumerable properties of an object, including inherited properties from its prototype chain.It is commonly used for iterating over the keys (property names) of an object.It should
1 min read
Nesting For Loops in JavaScript
Nesting for loops is crucial in JavaScript, enabling iteration over multi-dimensional data structures or performing complex tasks. It involves placing one loop inside another, where the outer loop executes for each iteration of the inner loop. This facilitates operations on multi-dimensional arrays or creating intricate patterns, essential for effi
4 min read
Concept of JavaScript Closures Inside Loops
JavaScript is a versatile language that is used extensively for creating interactive web applications. One of its unique features is the ability to create closures, which are functions that have access to variables in their outer scope. Closures can be a powerful tool in programming, but they can also be tricky to work with, especially when used in
5 min read
7 Loops of JavaScript
As a programmer, it's crucial to comprehend loops since they give you a means to repeatedly run a block of code. Loops are a fundamental idea in computer programming. Using loops has a number of advantages: Your code will be more effective if you use loops to automate repetitive processes and carry out the same actions repeatedly with little code.T
3 min read
C | Loops & Control Structure | Question 1
#include <stdio.h> int main() { int i = 1024; for (; i; i >>= 1) printf("GeeksQuiz"); return 0; } How many times will GeeksQuiz be printed in the above program? (A) 10 (B) 11 (C) Infinite (D) The program will show compile-time error Answer: (B) Explanation: In for loop, mentioning expression is optional. >>= is a composi
1 min read
C | Loops & Control Structure | Question 2
C/C++ Code #include #define PRINT(i, limit) do \\ { \\ if (i++ How many times GeeksQuiz is printed in the above program ? (A)1 (B)3 (C)4 (D)Compile-time error Answer: (A)Explanation: If a macro needs to be expanded in multiple lines, it is the best practice to write those lines within do{ }while(0) to avoid macro side effects. After GeeksQuiz is pr
1 min read
C | Loops & Control Structure | Question 3
What is the output of the below program? C/C++ Code #include int main() { int i = 2; switch (i) { case 0: printf("Geeks"); break; case 1: printf("Quiz"); break; default: printf("GeeksQuiz"); } return 0; } (A) Geeks (B) Quiz (C) GeeksQuiz (D) Compile-time error Answer: (C) Explanation: As i=2, so GeeksQuiz is printed. Quiz of this Question Please co
1 min read
C | Loops & Control Structure | Question 4
C/C++ Code #include int main() { int i = 3; switch (i) { case 1: printf("Geeks"); break; case 1+2: printf("Quiz"); break; default: printf("GeeksQuiz"); } return 0; } What is the output of the above program? (A) Geeks (B) Quiz (C) GeeksQuiz (D) Compile-time error Answer: (B) Explanation: Expression gets evaluated in cases. The control goes to the se
1 min read
C | Loops & Control Structure | Question 5
Predict the output of the below program: C/C++ Code #include #define EVEN 0 #define ODD 1 int main() { int i = 3; switch (i % 2) { case EVEN: printf("Even"); break; case ODD: printf("Odd"); break; default: printf("Default"); } return 0; } (A) Even (B) Odd (C) Default (D) Compile-time error Answer: (B) Explanation: The following C code will print 'o
1 min read
C | Loops & Control Structure | Question 6
C/C++ Code #include int main() { int i; if (printf("0")) i = 3; else i = 5; printf("%d", i); return 0; } Predict the output of above program? (A) 3 (B) 5 (C) 03 (D) 05 Answer: (C) Explanation: The control first goes to the if statement where 0 is printed. The printf(\"0\") returns the number of characters being printed i.e. 1. The block under if st
1 min read
C | Loops & Control Structure | Question 7
C/C++ Code #include int i; int main() { if (i) { // Do nothing } else { printf("Else"); } return 0; } What is correct about the above program? (A) if block is executed. (B) else block is executed. (C) It is unpredictable as i is not initialized. (D) Error: misplaced else Answer: (B) Explanation: Since i is defined globally, it is initialized with d
1 min read
C | Loops & Control Structure | Question 8
#include<stdio.h> int main() { int n; for (n = 9; n!=0; n--) printf("n = %d", n--); return 0; } What is the output? (A) 9 7 5 3 1 (B) 9 8 7 6 5 4 3 2 1 (C) Infinite Loop (D) 9 7 5 3 Answer: (C) Explanation: The program goes in an infinite loop because n is never zero when loop condition (n != 0) is checked. n changes like 9 7 5 3 1
1 min read
C | Loops & Control Structure | Question 9
Output? #include <stdio.h> int main() { int c = 5, no = 10; do { no /= c; } while(c--); printf ("%d\n", no); return 0; } (A) 1 (B) Runtime Error (C) 0 (D) Compiler Error Answer: (B) Explanation: There is a bug in the above program. It goes inside the do-while loop for c = 0. Also as the increment is post increment, so (no/0) will cr
1 min read
C | Loops & Control Structure | Question 10
# include <stdio.h> int main() { int i = 0; for (i=0; i<20; i++) { switch(i) { case 0: i += 5; case 1: i += 2; case 5: i += 5; default: i += 4; break; } printf("%d ", i); } return 0; } (A) 5 10 15 20 (B) 7 12 17 22 (C) 16 21 (D) Compiler Error Answer: (C) Explanation: Initially i = 0. Since case 0 is true i becomes 5, and since t
1 min read
C | Loops & Control Structure | Question 11
Output of following C program? #include<stdio.h> int main() { int i = 0; for (printf("1st\n"); i < 2 && printf("2nd\n"); ++i && printf("3rd\n")) { printf("*\n"); } return 0; } (A) 1st 2nd * 3rd 2nd * (B) 1st 2nd * 3rd 2nd * 3rd (C) 1st 2nd 3rd * 2nd 3rd (D) 1st 2nd 3rd * 1st 2nd 3rd A
1 min read
C | Loops & Control Structure | Question 12
#include <stdio.h> int main() { int i; for (i = 1; i != 10; i += 2) printf(" GeeksQuiz "); return 0; } (A) GeeksQuiz GeeksQuiz GeeksQuiz GeeksQuiz GeeksQuiz (B) GeeksQuiz GeeksQuiz GeeksQuiz .... infinite times (C) GeeksQuiz GeeksQuiz GeeksQuiz GeeksQuiz (D) GeeksQuiz GeeksQuiz GeeksQuiz GeeksQuiz GeeksQuiz GeeksQuiz Answer: (B) Exp
1 min read
C | Loops & Control Structure | Question 13
What will be the output of the following C program segment? (GATE CS 2012) char inchar = 'A'; switch (inchar) { case 'A' : printf ("choice A \n") ; case 'B' : printf ("choice B ") ; case 'C' : case 'D' : case 'E' : default: printf ("No Choice") ; } (A) No choice (B) Choice A (C) Choice A Choice B No choice (D) Program
1 min read
C | Loops & Control Structure | Question 14
Predict the output of the below program: #include <stdio.h> int main() { int i = 3; switch(i) { printf("Outside "); case 1: printf("Geeks"); break; case 2: printf("Quiz"); break; defau1t: printf("GeeksQuiz"); } return 0; } (A) Outside GeeksQuiz (B) GeeksQuiz (C) Nothing gets printed Answer: (C) Explanat
1 min read
C | Loops & Control Structure | Question 15
In the following program, X represents the Data Type of the variable check. #include <stdio.h> int main() { X check; switch (check) { // Some case labels } return 0; } Which of the following cannot represent X? (A) int (B) char (C) enum (D) float Answer: (D) Explanation: A switch expression can be int, char and enum. A float variable/expressi
1 min read
C | Loops & Control Structure | Question 16
What is the output of the following program? #include <stdio.h> int main() { char check = 'a'; switch (check) { case 'a' || 1: printf("Geeks "); case 'b' || 2: printf("Quiz "); break; default: printf("GeeksQuiz"); } return 0; } (A) Geeks (B) Geeks Quiz (C) Geeks Quiz GeeksQuiz (D) Compile-time error Answer: (D) E
1 min read
C | Loops & Control Structure | Question 17
Predict the output of the following program: #include <stdio.h> int main() { int check = 20, arr[] = {10, 20, 30}; switch (check) { case arr[0]: printf("Geeks "); case arr[1]: printf("Quiz "); case arr[2]: printf("GeeksQuiz"); } return 0; } (A) Quiz (B) Quiz GeeksQuiz (C) GeeksQuiz (D) Compile-time error Answer:
1 min read
C | Loops & Control Structure | Question 18
How many times GeeksQuiz is printed #include<stdio.h> int main() { int i = -5; while (i <= 5) { if (i >= 0) break; else { i++; continue; } printf("GeeksQuiz"); } return 0; } (A) 10 times (B) 5 times (C) Infinite times (D) 0 times Answer: (D) Explanation: The loop keeps incrementing i while it is smaller than 0. When i becomes
1 min read
C | Loops & Control Structure | Question 19
#include <stdio.h> int main() { int i = 3; while (i--) { int i = 100; i--; printf("%d ", i); } return 0; } (A) Infinite Loop (B) 99 99 99 (C) 99 98 97 (D) 2 2 2 Answer: (B) Explanation: Note that the i–- in the statement while(i-–) changes the i of main() And i== just after declaration statement int i=100; changes local i of while l
1 min read
C | Loops & Control Structure | Question 20
#include <stdio.h> int main() { int x = 3; if (x == 2); x = 0; if (x == 3) x++; else x += 2; printf("x = %d", x); return 0; } (A) x = 4 (B) x = 2 (C) Compiler Error (D) x = 0 Answer: (B) Explanation: Value of x would be 2. Note the semicolon after first if statement. x becomes 0 after the first if statement. So control goes to else
1 min read
C | Loops & Control Structure | Question 21
#include&lt;stdio.h&gt; int main() { int a = 5; switch(a) { default: a = 4; case 6: a--; case 5: a = a+1; case 1: a = a-1; } printf(&quot;%d \n&quot;, a); return 0; } (A) 3 (B) 4 (C) 5 (D) None of these Answer: (C) Explanation: There is no break statement, so first a = a + 1 is executed, then a = a-1 is executed. Quiz of this Questi
1 min read
Output of Python Programs | Set 23 (String in loops)
Prerequisite: Loops and String Note: Output of all these programs is tested on Python3 1. What is the output of the following? my_string = "geeksforgeeks" i = "i" while i in my_string: print(i, end =" ") None geeksforgeeks i i i i i i … g e e k s f o r g e e k s Output: 1. None Explanation: 'i' is not present in string
2 min read
PHP break (Single and Nested Loops)
In PHP break is used to immediately terminate the loop and the program control resumes at the next statement following the loop. Method 1: Given an array the task is to run a loop and display all the values in array and terminate the loop when encounter 5. Examples: Input : array1 = array( 1, 2, 3, 4, 5, 6, 7 ) Output : 1 2 3 4 Loop Terminated The
2 min read
ES6 Loops
Loops are the way to do the same task again and again in a cyclic way. A loop represents a set of instructions that must be repeated. In a loop’s context, a repetition is termed as an iteration. The following figure illustrates the classification of loops: Definite: There are three types of Definite loops in ES6. Each of them is described below wit
6 min read
Nested Loops in C++ with Examples
Nested loop means a loop statement inside another loop statement. That is why nested loops are also called as "loop inside loop". Syntax for Nested For loop: for ( initialization; condition; increment ) { for ( initialization; condition; increment ) { // statement of inside loop } // statement of outer loop } Syntax for Nested While loop: while(con
3 min read