For Loop In JavaScript

avatar

image.png

Image Source

For loop is one of the major and most important iterative control statement in JavaScript. It is used to perform same task again and again until the condition defined for the looping is evaluated to false. We use for loop when we know how many times the iteration is to performed in advance. The basic syntax of for loop is as below:

for (counter, condition test, update counter)
{
 //statement to be executed.
}

The brackets for for() contain several parameters separated by semicolons. The first one is the counter or the variable initialization from which you want to start your loop, the second one is the condition that specifies how many times you want to perform the iteration and the third one is updating your counter variable. Updation is usually an increment or decrement. Below we will see a simple example of a for loop that iterates through a character we declared. At each iteration it will print the characters having length equal to the iteration steps.

For example we defined a variable named "javascript". In first iteration, it will print j and is second loop, it will print ja and it continues on. Our loop condition is that we want to run until the value of i is less than the length of string which is 10. We created an empty string and at each iteration, the empty string is concatenated with the first letter of our character.

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript While Loop</title>
<script>
    name = "javascript";
    result = "";
   for (var i=0; i < name.length; i++)
   {
       result = result + name[i];
       document.write("<br>")
       document.write(result);
   }
</script>
</head>
<body>
</body>
</html>

You will get the following tree like output on your browser screen:

image.png



0
0
0.000
0 comments