Common JavaScript Manual/While and For loops

From Wikibooks, open books for an open world
Jump to: navigation, search

While[edit]

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

For[edit]

"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