Loops and Iteration
Overview
Repeating code is a common task in programming. JavaScript provides several loop statements, including
for, while, do...while, for...of, and for...in.
Each has a specific use case and syntax. Arrays also have a forEach method that calls a function
once for each item in the array.
Use for...of to loop over the values of an array. for...in loops over the
property names (keys) of an object and is not recommended for arrays.
Prepare
- Read: Loops and Iteration – MDN
- Reference: for...of and for...in – MDN
Check Your Understanding
- Given the following variable declarations:
const DAYS = 6; const LIMIT = 30; const studentReport = [11, 42, 33, 64, 29, 37, 44];- Write a
forloop that iterates through thestudentReportarray and prints each value that is belowLIMITto the console. - Repeat the first exercise using a
whileloop. - Repeat the first exercise using the
forEachmethod. - Repeat the first exercise using a
for...ofloop. - Use any type of loop to produce the day names (Monday, Tuesday, Wednesday, etc.) of the next
DAYSdays from today's date.
Check Your Understanding – Example Answers
These are not the only correct answers.
// for loop for (let i = 0; i < studentReport.length; i++) { if (studentReport[i] < LIMIT) { console.log(studentReport[i]); } } // while loop let index = 0; while (index < studentReport.length) { if (studentReport[index] < LIMIT) { console.log(studentReport[index]); } index++; } // forEach method studentReport.forEach((score) => { if (score < LIMIT) { console.log(score); } }); // for...of loop for (const score of studentReport) { if (score < LIMIT) { console.log(score); } }Use this CodePen to guide you to a solution for the last exercise. You will need to sift through the example code to find what applies.
CodePen ☼ JavaScript – Get Future Days from Today
- Write a