WebDevelopersNotes logo

home-icon Home / JavaScript / Understanding JavaScript for Loop

Understanding JavaScript for Loop

Understanding JavaScript for Loop

The main strength of any programming language is its ability to process blocks of code repeatedly. Computers are especially adept at performing repeated calculations. JavaScript, like other programming languages, provides us with loop. Statements placed inside loops are executed a set number of times… or even infinitely.

We’ll look at the for loop in this session. The while and do…while will be explained in the next session.

Here is the format of a for loop:

for (Initialization statements; Condition; Updation statements)
   {
   ...
   statements
   ...
   }

When the JavaScript interpreter comes across a for loop, it executes the initialization statements and then checks the condition. Only when the condition returns ‘true’, the interpreter enters the loop. After the first iteration, the updation statements are executed and then the condition is evaluated again. This continues till the condition returns ‘false’ and the loop stops.

Sponsored Links

Some important points to not for the JavaScript “for” loop

  • The initialization statements are executed once; only when the for loop is encountered.
  • After execution of initialization statements, the condition is evaluated.
  • After every iteration, the updation statements are executed and then the condition is checked.

We can use a for loop to print digits 1 to 10 in an alert box.

var msg = "";

for (var x = 1; x <= 10; x++)
   {
   msg = msg + x + "\n";
   }

alert(msg);

Click here for results

First, the variable x is initialized to 1, the condition is then evaluated. Since x is less than equal to 10, the statements inside the for loop are executed. The JavaScript interpreter then runs the updation statement that adds 1 to variable x. The condition is again checked. This goes on till the value of x becomes larger than 10. At this point, the statement immediately following the for loop is executed.

Displaying the 12 times table in an alert box

var msg = "";
var res = "0";

for (var x = 1; x <= 12; x++)
   {
   res = 12 * x;
   msg = msg + "12 X " + x + " = " + res + "\n";
   }

alert(msg);

Click here for results

Sponsored Links

Your comments
Star icon IMPORTANT Have a question / problem? Click here to ask an expert.

Caps Lock jokes and funny images

Sponsored Links

Tips

How do I view a deleted web page?
Is there a way to view a deleted web page - one that is no longer available? Yes there is and the solution is quite simple. [more...]

Fact

If you're using the default genie effect, hold down the shift key and then minimise a window. The window will now drop to the Dock in slow-mo. [more...]