JavaScript For Loop | complete reference

Javascript loop statements or the type of the loops like javascript for loop is used for executing the block of the code number of times.

Syntax: JavaScript For Loop

for ([initialExpression]; [condition]; [incrementExpression])
  statement
for (statement 1; statement 2; statement 3) {
  // code block to be executed
}
  • Statement 1 is executed one time before the execution of code blocks.
  • In statement 2 you put the condition for the loop.
  • In statement 3, it is executed after the code block has been executed.
javascript for loop

JavaScript For Loop

Loops are very user-friendly when you want to use the same code again and again with different values you can use the JavaScript For Loop.

Iterative Loop Method

An iterative loop method, if you want to print Hello World 5 times using JS,

<script type = "text/javascript"> 
document.write("Hello World\n"); 
document.write("Hello World\n"); 
document.write("Hello World\n"); 
document.write("Hello World\n"); 
document.write("Hello World\n"); 
</script>

Using JavaScript For Loop Method

In JavaScript for loop, the code is written once and the loop will be executed that code N number of times which is user put on that.


<script type = "text/javascript"> 
var i; 
  
for (i = 0; i < 6; i++)  
{ 
    document.write("Hello World!\n"); 
} 
</script>

JavaScript | For/In Loop

In JavaScript Loop, For/In Loop is used for the loop-through properties of an object.

<p id="here"></p>

<script>
var txt = "";
var details = {fname:"John", lname:"Man", age:20}; 
var x;
for (x in details) {
  txt += details[x] + " ";
}
document.getElementById("here").innerHTML = txt;
</script>

John Man 20

OutPut

JavaScript | For/Of Loop

For Loop Over An Array

Syntax: Loop Over An Array

for (variable of iterable) {
  // code block here
}

Example:

var names = ['John', 'Doe', 'Mini'];
var y;

for (y of names) {
  document.write(y + "<br >");
} 

John
Doe
Mini

OutPut

Loop Over a String

Using “of” we loop over the strings. Check the below example about that,

var text = 'JavaScript';
var y;

for (y of text) {
  document.write(x + "<br >");
} 

J
a
v
a
S
c
r
i
p
t

OutPut

Happy Coding..!

Add a Comment

Your email address will not be published. Required fields are marked *