+ 1
What is javascript loop ? How to use js loops. I don't understand Please can anyone tell me.
2 Answers
+ 3
Loops are a way to repeat some action. Essentially you can use 3 loops types: for, while, do..while.
Obliviously would be a way to control how many times your loop must be exceuted (how many iterations). Lets go to see the for loop:
for(init; condition; postExecution){
statements
}
- init: Here you can place some statement that init something. Ususally its used for init a variable thats used in condition and in postExecution
- condition: This is an expression valutated like a boolean value (true or false) and your loop will run while this expression is true (except some cases)
- postExecution: This is an expression executed AFTER any iteration of your loop
Example (javascript):
for(var i=0; i<10; ++i){
console.log(i);
}
In the previous example, in "init" i placed an initialization of a var "i" that will contain current iteration index (starting from 0). In "condition" i putted an expression that indicate while this loop while this loop can run. In this case, while i its less than 10. All this will made an infinite loop if i wouldnt add something that change "i" value, then, i putted in "postCondition" field an statement that increment this variable "i". Note that i would have put at end of "statement" and get same result like:
for(var i=0; i<10;){
console.log(i);
++i;
}
Note that semicolons are MANDATORY though you dont place one of "init" or "postExecution".
Well, this will make following output:
0
1
2
3
4
5
6
7
8
9
Because this happen:
1) init is valuted (var i=0;) then a "i" var its avaible
2) At any iteration check if "i" is less than 10
3) execute "statements" (the for body) if condition is satisfied (contition valued to true) else end the loop
4) postExecution is valuted (++i). This increment i by one. Go to step 2
+ 3
while loop its same like loop BUT you can place only the condition, then you can write same code using "while" so:
var i=0;
while(i<10){
console.log(i);
++i;
}
do...while its essentially a while that execute least one iteration
var i=0;
do{
console.log(i);
++i;
}while(i<10);
Note that if you init i to a number greater or equals than 10 AN ITERATION ITS EXECUTED because condition is checked after the iteration... In practice happen:
1) execute do...while
2) check condition, if its satisfied continue with loop else stop the iterations
Warn that exist other way to iterate but these are the basic ways