-Intro to For Loops
-More For Loops Examples
-The Perils of Infinite Loops
-Looping Over Arrays
-Nested Loops
-While-Loop
-Break Keyword
Intro to For Loops
Loops allow us to repeat code
There are multiple types:
for loops, while loops, for...of loop, for..in loop
for loop
for (let i = 1; i <= 10; i++) {
console.log(i);
}
Looping Over Arrays
It is possible to loop over arrays.
const animals = [ 'lions', 'tigers', 'bears' ];
for (let i = 0; i < animals.length; i++) {
console.log(i, animals[i]);
}
Nested Loops
It is possible to have a loop within a loop
let str = 'LOL';
for(let i = 0; i <= 4; i++) {
console.log("Outer:", i);
for (let j = 0; j < str.length; j++) {
console.log(' Inner:', str[j]);
}
}
While-Loop
While loops continue running as long as the test conditional is true.
let num = 0;
while (num < 10) {
console.log(num);
num++;
}
Break Keyword
let targetNum = Math.floor(Math.random() * 10);
let guess = Math.floor(Math.random() * 10);
while (true) {
guess = Math.floor(Math.random() * 10);
if (guess === targetNum) {
console.log(`Correct! Guessed: ${guess} & target was: ${targetNum} `);
break;
}
else {
console.log(`Guessed ${guess}...Incorrect!`);
}
}
The break keyword is used with while loops, although technically you can use it with other loops, its just rare.
Top comments (0)