For Loop In JavaScript

- For Loop
- For...In Loop
- For...of Loop
- While Loop
- Do While Loop
For Loop in JavaScript
For Loop will run the same code of block again and again repeatedly, for a specific number of time or as long as a certain condition is met. The For loop of JavaScript is similar to C language and Java for Loop.Syntax for (initialization; condition; final expression) { // code to be executed }The for loop is the most concise part of looping. There is three expression use in for Loop initialization, condition, and final expression.
For Loop Syntax in JavaScript
- The first step is initialization where you have to assign a value to a variable and that variable will be used inside the loop. The initial statement is executed before the loop begin.
- The test condition or statement will evaluate that if it is true or false. And if it would be true then the loop statement executes or otherwise, the execution of the loops ends.
- The final expression is the iteration statement where you can increase or decrease your statement.
Optional Expressions in Javascript For Loop
All of these three expressions in for loop are optional. we can write the for statements without initializations. Look at the demonstration for more clarity.// declare variables outside the loop var i = 5; for( ; i<10; i++;) { document.write("<p> 'The number is + i +' </p>") }Output
As you can see that it is necessary to put a semicolon ; whether it is empty. We can also remove the condition from the room. For this, we can use if statement combined with a break. This break is for the loop to stop running once i is greater than 10.
- The number is 5
- The number is 6
- The number is 7
- The number is 8
- The number is 9
// declare variables outside the loop var i = 5; for( ; ; i++;) { if(i < 10) { break } document.write("<p> 'The number is + i +' </p>") }Output
The number is 5 The number is 6 The number is 7 The number is 8 The number is 9Never forget to add the break statement. Unless the loop will run forever and potentially break the browser.
// Declare variable outside the loop let i = 0; // leave out all statements for ( ; ; ) { if (i > 3) { break; } document.write(i); i++; }Output
The number is 5 The number is 6 The number is 7 The number is 8 The number is 9
For...In Loop
Syntax for (variableName in Object) { statement }
Syntax for (variable of object) statement
×
![]()































































