Last modified on 21 February 2011, at 09:05

Common JavaScript Manual/While and For loops

WhileEdit

While expression looks so:

while(condition){
  codeInCycle
}

Here, if the condition is true then the code inside the loop and then the process goes first but if the condition is true then execution continues after the loop. Let's see example.

n = 2;
nums = [];
while(n < 16){
  nums.push(n++);
}
print(nums); //2,3,4,5,6,7,8,9,10,11,12,13,14,15

ForEdit

"For" cycle is a short form of while.

for(exp1;exp2;exp3){
  code
}
//Equal for
exp1;
while(exp2){
  code;
  exp3;
}

Let's rewrite our code.

for(n=2,nums=[];n<16;n++){
  nums.push(n);
}
print(nums); // 2,3,4,5,6,7,8,9,10,11,12,13,14,15

Conditional statements · Do .. While and For .. in loops