Iterate using JavaScript for loop

 Iterate using JavaScript for loop

We already know that loops are used to execute a block of code over and over again. The simplest was the while loop that we've already covered.

JavaScript for loops have three parameters. A start value, a end value and a increment/decrement value. The start value is used to specify where to being, the end value defines when to end looping and the increment/decrement values ++ and -- respectively.

Let's consider an example to understand this better. Here, we are iterating through all the elements in array. As long as the array.lenght condition is true, the loop continues. It contains five elements. Thus it will fail fourth time.

<!DOCTYPE html>
<html lang="en">
    <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>Using for loops</title>
    <div id="res"></div>
        var res = document.getElementById("res");

        var numberArray = [1,2,3,4,5];
        res.innerText += "\n" + numberArray[i];

Assignment: Iterate numbers in array from 10 to 1 in reverse order.

Post a Comment