Home / JavaScript / 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.
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);
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.
var msg = ""; var res = "0"; for (var x = 1; x <= 12; x++) { res = 12 * x; msg = msg + "12 X " + x + " = " + res + "\n"; } alert(msg);
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...]
The iPad wasn't the first tablet from Apple. The company had produced Newton MessagePad way back in 1993. The MessagePad had a stylus, something that Steve Jobs specifically didn't want on the iPad. [more...]
We use cookies to give you the best possible website experience. By using WebDevelopersNotes.com, you agree to our Privacy Policy