DEV Community

Code_Regina
Code_Regina

Posted on

|JavaScript| JavaScript: Repeating Stuff with Loops

          -Intro to For Loops
          -More For Loops Examples
          -The Perils of Infinite Loops
          -Looping Over Arrays
          -Nested Loops
          -While-Loop
          -Break Keyword
Enter fullscreen mode Exit fullscreen mode

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); 
}

Enter fullscreen mode Exit fullscreen mode

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]); 
}


Enter fullscreen mode Exit fullscreen mode

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]); 
}
}
Enter fullscreen mode Exit fullscreen mode

While-Loop

While loops continue running as long as the test conditional is true.


let num = 0; 
while (num < 10) {
  console.log(num); 
  num++;
}

Enter fullscreen mode Exit fullscreen mode

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!`); 
}
}

Enter fullscreen mode Exit fullscreen mode

The break keyword is used with while loops, although technically you can use it with other loops, its just rare.

Top comments (0)