Stats

284 Contributors: 20 Monday, July 24, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Loops

Syntax

  • for (initialization; condition; final_expression) { }
  • for (key in object) { }
  • for (variable of iterable) { }
  • while (condition) { }
  • do { } while (condition)
  • for each (variable in object) { } // ECMAScript for XML

Remarks

Loops in JavaScript typically help solve problems which involve repeating specific code x amount of times. Say you need to log a message 5 times. You could do this:

console.log("a message");
console.log("a message");
console.log("a message");
console.log("a message");
console.log("a message");

But that's just time-consuming and kind of ridiculous. Plus, what if you needed to log over 300 messages? You should replace the code with a traditional "for" loop:

for(var i = 0; i < 5; i++){
    console.log("a message");
}

Related Examples