code

JavaScript For Loops

// For Each Loop

collection.forEach(function(item, index, array) {
   console.log(item, index)
})

// typical counting up
var ourArray = [];
for (var i = 0; i < 5; i++) {
  ourArray.push(i);
}

// backwards by 2
var ourArray = [];
for (var i = 10; i > 0; i -= 2) {
  ourArray.push(i);
}

// iterate through array
var arr = [10, 9, 8, 7, 6];
for (var i = 0; i < arr.length; i++) {
   console.log(arr[i]);
}

// nested array iteration
var arr = [
  [1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
  for (var j=0; j < arr[i].length; j++) {
    console.log(arr[i][j]);
  }
}

Leave a Reply

Matt is the author of five Apress books including Learn RStudio IDE, Quick, Effective, and Productive Data Science, Objective-C Recipes, Swift Quick Syntax Reference, Objective-C Quick Reference, and the upcoming Pro Data Visualization with R and JavaScript. He has over 20 years of experience in technology, psychometrics, and data analytics working in major higher education institutions such as The College Board and Educational Testing Service. He has earned a Master’s degree in Information Systems Management and a Bachelor’s degree in Quantitative Psychology.