We need to run sometime some code/operation common for multiple elements in a list or array. Hence we need to loop.
Java script for loop have 3 part.
- initialization of variable
- test condition w.r.t to variable
- counter- could be increment or decrement
- first it will do the initialization and test check the condition, if condition is  true , it will execute the block else exit the for loop.
- it will execute the block until the condition is true.
Syntax:
1 2 3 |
for (initialization; test condition; counter) { Statement(s) to be executed if test condition is true } |
Example code;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="div1"></p> <script type="text/javascript"> const fruits = ["apple", "banana", "orange", "guava"]; let text = ""; for (let i = 0; i < fruits.length; i++) { text += fruits[i] + "<br>"; } document.getElementById("div1").innerHTML = text; </script> </body> </html> |
Output:
apple
banana
orange
guava