JavaScript Loops


JavaScript Loops

Loops come in handy when you need to run the same lines of code repeatedly, for a set number of times or as long as a certain condition is true. You want to input the word "Hello" 100 times on your website, and you'll have to copy and paste the same line 100 times, of course. Instead, you may perform this work in just 3 or 4 lines if you utilize loops.

JavaScript has all of the required loops to make programming easier.

The For Loop

It is a loop that repeats itself. The 'for' loop is the smallest type of loop, and it consists of the three key components listed below:

  1. The startup of the loop, when we set our counter to a beginning value. Before the loop starts, the initialization statement is executed.
  2. The test statement determines whether or not a particular condition is true. If the condition is true, the code inside the loop will be performed; if it is false, the control will exit it.
  3. You can increase or reduce your counter with the iteration statement. All three components can be written on a single line, separated by semicolons.

All three components can be written on a single line, separated by semicolons.

Example No.1:

<html> <body> <h2>Knowledge2life</h2> <p id="demo"></p> <script> const cars = ["Knowledge2life 1", "Knowledge2life 2", "Knowledge2life 3", "Knowledge2life 4"]; let text = ""; for (let i = 0; i < cars.length; i++) { text += cars[i] + "<br>"; } document.getElementById("demo").innerHTML = text; </script> </body> </html>

OUTPUT:

Knowledge2life

Knowledge2life 1
Knowledge2life 2
Knowledge2life 3
Knowledge2life 4

Example No.2:

<html> <body> <h2>Knowledge2life</h2> <p id="demo"></p> <script> let text = ""; for (let i = 0; i < 5; i++) { text += "Knowledge2life " + i + "<br>"; } document.getElementById("demo").innerHTML = text; </script> </body> </html>

OUTPUT:

Knowledge2life

Knowledge2life 0
Knowledge2life 1
Knowledge2life 2
Knowledge2life 3
Knowledge2life 4