DEV Community

Cover image for Looping with for...of and While Loops
Saoud
Saoud

Posted on

Looping with for...of and While Loops

Looping with for...of

Terminology


  • for...of: A technique we can use to loop through arrays, strings, and other types of iterable objects.

Examples


Example Using an Array

const array = [0,1,2,3,4,5];
let doubledArray = [];
for (const element of array) {
  doubledArray.push(element * 2);
}
doubledArray;
Enter fullscreen mode Exit fullscreen mode

Example Using a String

const consonantString = "bdfmxtgl"
let vowelizedString = "";
for (const letter of consonantString) {
  vowelizedString = vowelizedString.concat(letter + "a");
}
vowelizedString;
Enter fullscreen mode Exit fullscreen mode

While Loops

Terminology


  • while: A type of loop that runs until a condition is met.

Examples


Example of while Loop

let number = 10;
while (number > 0) {
  console.log(number);
  number --;
}
console.log("Blast off!")
Enter fullscreen mode Exit fullscreen mode

Example of do...while Loop

let number = 10;
do {
  console.log(number);
    number --;
} while (number > 0);
console.log("Blast off!");
Enter fullscreen mode Exit fullscreen mode

Top comments (0)