Loops
Using a loop simply means : Repeat this code until some condition is true
while loop
while (condition) {
// code to be executed while the condition is true
}
The while loop in JS
- the condition : once the condition is
false
, the loop will end;- the code to execute : the purpose of the loop is to run some code a certain number of times.
let counter = 1;
while (counter <= 10){
console.log(counter);
counter += 1;
}
While loop in grpah
for loop
for
loop is much like the while
loop, except that some of the functionalities you had to do on your ownn are included in it. for loop
: i
will be started from 1
and incremented 1
until the 10
.for (let i = 1; i <= 10; i++)
{
console.log(i);
}
Nested loops
Fizbuzz
// Creating the loop...
for (let i = 1; i <= 50; i++) {
// when at least one condition is true, run the code
if (i % 10 === 0 || i % 15 === 0) {
console.log('Donkey!');
}
// when both conditions are true, run the code
if (i % 2 !== 0 && (i - 1) % 10 !== 0) {
console.log('Monkey!');
}
// on numbers divisible by 5, continue to the next iteration
if (i % 5 === 0) {
continue;
}
// ... and console.log the variable i
console.log(i);
}