For Loop

What are Loops?

Loops are useful when you have to execute the same lines of code repeatedly, for a specific number of times or as long as a specific condition is true. For Loop

Suppose you want to run a particular code for 100 times Of course, you will have to copy and paste the same code 100 times. Instead, if you use loops, you can complete this task in just 3 or 4 lines.

There are four types of loops in JavaScript.

  1. for loop
  2. while loop
  3. do-while loop
  4. for-in loop

In this article we learn about for-loop….

for-loop: is the most commonly used looping technique. The reason why it is so popular is because it has all the three parts of the loop: initializationtest expression, update expression in the same line. The syntax of a for loop is:

initialization is executed before the loop (the code block) starts.

test expression defines the condition for running the loop (the code block).

update expression is executed each time after the loop (the code block) has been executed.

for(initialization; test expression; update expression)

{

 //body of loop

}
// program to display text 5 times
const n = 5;

// looping from i = 1 to 5
for (let i = 1; i <= n; i++) {
    console.log('Welcome to fullstackadda.com');
}
Welcome to fullstackadda.com
Welcome to fullstackadda.com
Welcome to fullstackadda.com
Welcome to fullstackadda.com
Welcome to fullstackadda.com

Example 2: For Loop

Program to display numbers from 1 to 5

const n = 5;
for (let i = 1; i <= n; i++) {
    console.log(i);     // printing the value of i
}
1
2
3
4
5
for loop

  1. JavaScript loops are used to iterate the piece of code repeatedly.
  2. For loop has all the three parts of the loop: initialization, test expression, update expression in the same line.

.