Nov
23
2015
By abernal
Loops are useful to iterate a given number of times based on a given condition
While loop
Syntax
while(condition){ // code }
Sample
var amountOfIterations = 10; var currentIteration = 1; while (currentIteration <= amountOfIterations){ console.log("this is the current iteration : " + currentIteration ); currentIteration++; }
For loop
Syntax
for(*start with this* ; *loop if this expression is true * ; *do this after each loop*){ // code }
Sample
var amountOfIterations = 10; for(var currentIteration = 1; currentIteration <= amountOfIterations ; currentIteration++){ console.log("this is the current iteration : " + currentIteration ); } // Other Sample Array.prototype.countCattle = function(kind) { var numKind = 0; for (var i; i < this.length; i++){ if (this[i].type == kind ){ numKind++; } } return numKind; };