About for loops with Example in JavaScript

Loops are used in programming to automate repetitive tasks. The most basic types of loops used in JavaScript are the while and do…while statements, which you can review in “How To Construct While and Do…While Loops in JavaScript.”

Because while and do…while statements are conditionally based, they execute when a given statement returns as evaluating to true. Similar in that they are also conditionally based, for statements also include extra features such as a loop counter, allowing you to set the number of iterations of the loop beforehand.

In this tutorial, we will learn about the for statement, including the for…of and for…in statements, which are essential elements of the JavaScript programming language.

For loop:

In computer science, a for-loop (or simply for loop) is a control flow statement for specifying iteration, which allows code to be executed repeatedly. Various keywords are used to specify this statement: descendants of ALGOL use “for”, while descendants of Fortran use “do”. There are other possibilities, for example COBOL which uses “PERFORM VARYING”.

JavaScript Loop:

Imagine you have to write a program which performs a repetitive task such as counting from 1 to 100. Coding 100 lines to do this task would be mundane. There has to be an easier way, right? This is where loops come into the picture. MCQ Loops are specifically designed to perform repetitive tasks with one set of code. Loops save alot of time.

JavaScript For Loop:

The ‘Javascript for loop‘ is the most compact form of looping. It includes the following three important parts −

  • The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
  • The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of the loop.
  • The iteration statement where you can increase or decrease your counter.

You can put all the three parts in a single line separated by semicolons.

Flow Chart

The flow chart of a for loop in JavaScript would be as follows −

JavaScript - For Loop

The for loop is used to repeat a task a set number of times.

Syntax:

for(var a_variable = initial_value; a_variable < end_value; 
a_variable_increment){
code to be executed;
}

Example:

<script type="text/javascript">
for(var a = 1; a < 11; a++){
document.write(a + " ");
}
</script>
For loop in javascript result

The for loop has three parts:

  • variable declaration – The first part of the loop which initializes the variable at the beginning of the loop to some value. This value is the starting point of the loop.
  • condition – The second part of the loop, and it is the part that decides whether the loop will continue running or not. While the condition in the loop is true, it will continue running. Once the condition becomes false, the loop will stop.
  • increment statement – The increment statement is the third part of the loop. It is the part of the loop that changes the value of the variable created in the variable declaration part of the loop. The increment statement is the part of the loop which will eventually stop the loop from running.

Lets look at the earlier loop example step-by-step:

for(var a = 1; a < 11; a++){
document.write(a + " ");
}
  • var a = 1 – The variable declaration part of the loop. A variable named a is declared with a value of 1.
  • a < 11 – The condition of the loop. It states that as long as the variable a is less than 11, the loop should keep running.
  • a++ – The increment statement part of the loop. It states that for every iteration of the loop, the value of the variable a should increase by 1. Recall that initially a is 1.
  • document.write(a + ” “); – The actual code that executes in the loop. Will print a number with a single space for each iteration in the loop.

Another Example:
Try the following example to learn how a for loop works in JavaScript.

<html>
   <body>      
      <script type = "text/javascript">
         <!--
            var count;
            document.write("Starting Loop" + "<br />");
         
            for(count = 0; count < 10; count++) {
               document.write("Current Count : " + count );
               document.write("<br />");
            }         
            document.write("Loop stopped!");
         //-->
      </script>      
      <p>Set the variable to different value and then try...</p>
   </body>
</html>

Result/ Output:

Set the variable to different value and then try…

for-in loop

A for-in loop iterates through the properties of an object and executes the loop’s body once for each enumerable property of the object. Here is an example:

var student = { name:"Bill", age: 25, degree: "Masters" };
for (var item in student) {
alert(student[item]); // => "Bill", then 25, then "Masters"
}

With each iteration JavaScript assigns the name of the property (a string value) to the variable item. In the example above these are: name, age, and degree.

Note that for-in loops also return properties and methods that are inherited through the prototype chain. An easy way to skip properties and functions that are not part of the object itself use the built-in hasOwnProperty method.

var Student = function(name) {
this.name = name;
}
Student.prototype.age = 38;
var student = new Student("Carl");
for (var item in student) {
if (student.hasOwnProperty(item)) {
alert (student[item]); // => Carl. age is not displayed
}
}

We have not discussed objects yet, but the student object has a name property on the object itself. Its prototype object has an age property. The for-in loop iterates over all properties, but the hasOwnProperty ensures that the age property on the prototype does not get displayed because it is not student’s own property.

References:

https://www.w3schools.com
https://www.tutorialspoint.com/
http://www.landofcode.com
https://www.digitalocean.com
https://developer.mozilla.org

Leave a Reply

Menu