DEV Community

Cover image for Loop Types in JavaScript
Md. Injamul Alam
Md. Injamul Alam

Posted on

Loop Types in JavaScript

In this blog I'll go through different ways of looping in JavaScript with examples:

  • while
  • forEach
  • map
  • do while
  • for in
  • for of
  • for

while Loop

const developers = ['Injamul', 'Saurav', 'Tarek', 'Saiful'];

let developer = 0;

while (developer < developers.length) {
    console.log(developers[developer]);
    developer++;
}

/* Output: 
Injamul
Saurav
Tarek
Saiful
*/  
Enter fullscreen mode Exit fullscreen mode

forEach Loop

const developers = ['Injamul', 'Saurav', 'Tarek', 'Saiful'];

developers.forEach (developer =>{
    console.log(developer);
})

/* Output: 
Injamul
Saurav
Tarek
Saiful
*/  
Enter fullscreen mode Exit fullscreen mode

map Loop

const developers = ['Injamul', 'Saurav', 'Tarek', 'Saiful'];

developers.map (developer =>{
    console.log(developer);
    return developer;
})

/* Output: 
Injamul
Saurav
Tarek
Saiful
*/  
Enter fullscreen mode Exit fullscreen mode

do while Loop

const developers = ['Injamul', 'Saurav', 'Tarek', 'Saiful'];

let developer = 0
do {
    console.log(developers[developer]);
    developer++;
    }

while(developer < developers.length)

/* Output: 
Injamul
Saurav
Tarek
Saiful
*/  
Enter fullscreen mode Exit fullscreen mode

for of Loop

const developers = ['Injamul', 'Saurav', 'Tarek', 'Saiful'];

for (const developer of developers){
    console.log(developer);
    }

/* Output: 
Injamul
Saurav
Tarek
Saiful
*/  
Enter fullscreen mode Exit fullscreen mode

for in Loop

const developers = {
    1 : 'Injamul', 
    2 : 'Saurav', 
    3 : 'Tarek', 
    4 : 'Saiful'
};

for (const key in developers) {
    console.log(developers[key]);
}

/* Output: 
Injamul
Saurav
Tarek
Saiful
*/  
Enter fullscreen mode Exit fullscreen mode

for Loop

const developers = ['Injamul', 'Saurav', 'Tarek', 'Saiful'];

for (let developer = 0; developer < developers.length; developer++){
    console.log(developers[developer]);
    }

/* Output: 
Injamul
Saurav
Tarek
Saiful
*/  
Enter fullscreen mode Exit fullscreen mode

Top comments (0)