Looping in Java Script

 

Looping in Java Script

Looping allows you to repeat a set of actions multiple times, which can be very useful for tasks such as iterating through arrays or generating dynamic content.


The "for" loop: The for loop is used to execute a block of code a fixed number of times. 


for (let i = 0; i < 10; i++) {

  console.log(i);

}


The "while" loop: The while loop is used to execute a block of code as long as a specified condition is true.


let i = 0;

while (i < 10) {

  console.log(i);

  i++;

}


The "do-while" loop: The do-while loop is similar to the while loop, but it will always execute the block of code at least once, even if the condition is false. 


let i = 0;

do {

  console.log(i);

  i++;

} while (i < 10);



Example


<!DOCTYPE html>

<html>

<head>

<title>Looping Example</title>

</head>

<body>


<h1>Looping Example</h1>


<!-- Create a div to display the loop output -->

<div id="loop-output"></div>


<script>

// Use a for loop to iterate over the numbers 1 to 10

for (var i = 1; i <= 10; i++) {

// Build a string to display the current iteration value

var outputString = "Iteration " + i + " of the loop.";


// Display the output string in the div with the id "loop-output"

document.getElementById("loop-output").innerHTML += outputString + "<br>";

}

</script>


</body>

</html>


Post a Comment

Previous Post Next Post