JavaScript for Loop

You are Here:

JavaScript for Loop

The for loop executes a block of code for the specified number of times.

In the following example, we will write Hello world for 3 times.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>This for loop will execute 3 times.</p> <script> for(var i = 0; i < 3; i++) document.write("Hello world <br>"); </script> </body> </html>

Syntax

for(initialStatement; testCondition; updateStatement){ // code block }

More Examples

In the following example, we will display the numbers from 0 to 5.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); var txt = ""; for(var i = 0; i <= 5; i++) txt += i; x.innerText = txt; </script> </body> </html>

In the following example, we will display all the items in the array.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); var bike = ["KTM", "Honda", "Yamaha", "BMW"]; var txt = ""; for(var i = 0; i < bike.length; i++) txt += bike[i] +"<br>"; x.innerHTML = txt; </script> </body> </html>

In the following example, we will run a for loop for infinite number of times.

Note: We break the following infinite for loop after 10 iteration.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p id="point"></p> <script> var x = document.getElementById("point"); var txt = ""; var i = 0; for(;;){ if(i == 10) break; txt += i; i++; } x.innerText = txt; </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author