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
1 2 |
for ([initialExpression]; [condition]; [incrementExpression]) statement |
1 2 3 |
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
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,
1 2 3 4 5 6 7 |
<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.
1 2 3 4 5 6 7 8 9 10 |
<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.
1 2 3 4 5 6 7 8 9 10 11 |
<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
1 2 3 |
for (variable of iterable) { // code block here } |
Example:
1 2 3 4 5 6 |
var names = ['John', 'Doe', 'Mini']; var y; for (y of names) { document.write(y + "<br >"); } |
John
OutPut
Doe
Mini
Loop Over a String
Using “of” we loop over the strings. Check the below example about that,
1 2 3 4 5 6 |
var text = 'JavaScript'; var y; for (y of text) { document.write(x + "<br >"); } |
J
OutPut
a
v
a
S
c
r
i
p
t
https://en.wikipedia.org/wiki/JavaScript
Happy Coding..!
One Reply to “JavaScript For Loop | complete reference”