LOOPS - JS

For

Loop "For" is used to do a loop on a determinate number of element.

Simple example : For i from 0 to "n" we want to add i to the previous result.

const n = 10;
let result = 0;
for (let i = 0; i < n; i++) {
  result = result + i;
}
//result = 45

While

Loop "While" is used to do a loop on an indeterminate number of element !

Simple example : While i < p, add i to the result.

const p = 10;
let i = 1;
let result2 = 0;
while (i < p) {
 result2 = result2 + i;
  i++;
}
//result = 45

Was this article helpful?

Powered by Zendesk