mercredi 24 juillet 2013
JavaScript For Loop
The JavaScript FOR loop is the simplest and most frequently used looping command. It simply executes a block of code until a certain condition is met. On every cycle/loop, it will first check if the specified condition is true, if yes then it will execute the block of code within the curly brackets.
Syntax
For (Counter variable name and initial value ; Condition ; Increment;)
{
code lines to be executed
}
Initial value of the counter variable- Starting value.
Condition- to keep looping until the condition is true OR in other words stop as soon as condition gets False.
Increment- How to increment the value of counter variable on every loop.
Simple JavaScript For Loop Example
Create a mathematical table for the number 5, i.e. multiply it with numbers 1 to 10 and display results.
javascript for loop example
Step 1- We declared a variable called 'a' and assigned it a value of 5.
Step 2- We declared a variable called counter and assigned it a value of 1. We called it counter because its value will change every time the loop is run.
Step 3- The condition- Until the condition in the following round brackets is true (counter <= 10), execute the code in the curly brackets below.
Step 4- We then print on the screen, the number 5, multiplication symbol x, the current value of the variable counter and the result of 5 multiplied with the current value of counter.
First time the code is executed, 5 x 1 and the result is a *5 which is five.
Now the next time code is executed, all values remain same but the value of the variable counter is incremented by 1 as we instructed in the for command- counter++ which is same as counter = counter+1. So the second time the loop runs, a * counter is 5 * 2 which results in 10.
for loop result
Example-
Make a JavaScript Program for creating/displaying mathematical tables of any number that user wants
Much similar to the example above. Just that here we will ask the user to enter a number through a Prompt PopUp box, whose mathematical table she wants. Instead of incrementing the value of counter variable by 1, we will do it by 2 in this example.
Instead of providing a value for a, here user will enter a value in the prompt box, which we will assign to a.
advance for loop
Here we increment the value of the variable counter by 2. counter=counter + 2 means, the new value of counter is equal to the old value of counter + 2.
Once the value of counter becomes 11, it no longer meets the condition of < = 10. therefore the loop stops.
Result
A popup box will prompt the user to enter a number.
popup box JS for loops
Inscription à :
Publier les commentaires (Atom)
Aucun commentaire:
Enregistrer un commentaire