Advertisement

Advertisement


JavaScript Loops

Loops are used to execute a block of code a specified number of times. In JavaScript, there are many loops which can be used like for, while, do while or for-in loops.

Loops Description
for loops through a block of code a specified number of times.
for in The JavaScript for/in statement loops through the properties of an object.
while loops through a block of code as long as the specified condition is true.
do while loops through a block of code once, and then repeats the loop as long as the specified condition is true.

JavaScript For loop

The for loop iterates the block of code for a fixed number of times. It is used when the number of iteration is known. The syntax of for loop is given below.

Syntax
for (initialization; condition; increment/decrement)
{
// code to be executed
}

The parameters of the for loop statement have following meanings:

  • Initialization : It is used to give initial value to the counter variables, which after one loop will get incremented/decremented as specified.
  • Condition : It is evaluated at the beginning of each iteration. If it evaluates to true, then only the loop statements execute. If it evaluates to false, the execution of the loop ends.
  • Increment/Decrement : It updates the loop counter with a new value each time the loop runs.

Here in this example, firstly 'i' is initialized a value, then a condition is given to control the loop and then the increment operator is used to increment the value of 'i'. In this loop every value of 'i' will get printed on the screen till the given condition is true.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript For Loop Statement </title>
</head>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>

Output

JavaScript For Loop Statement


Here in the example below, an array storing 5 values is iterated by the help of for loop. The index value of the array is incremented with every loop and then one by one all the values of the array gets printed on the screen. Take a look in try-it editor to understand the working of for loop in arrays.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript For Loop Statement </title>
</head>
<body>
<script>
// An array with some elements
var Smartphone = ["Apple", "Google Pixel", "Samsung", "Asus", "Motorola"];
// Loop through all the elements in the array
for(var i=0; i<Smartphone.length; i++) {
document.write("<p>" + Smartphone[i] + "</p>");
}
</script>
</body>
</html>

Output

JavaScript For Loop Statement









Become a Patron!

Note: If the updated content is not visible to you please refresh the cookies by pressing CTRL + Shift + R.