Loops and Iteration
Overview
Repeating code is a common task in programming. JavaScript provides several ways to repeat
code including
for, while, do...while, and for...in
statements. Each of these
statements has a specific use case and syntax. forEach is a method that can be
used on arrays to
iterate over each item in the array.
Prepare
- Read 📝 Loops and Iteration - MDN web docs
Check Your Understanding
- Complete the activities presented in this resource: JavaScript Loops - WDD Learning Modules
- Given the following variable declarations:
const DAYS = 6; const LIMIT = 30; let studentReport = [11, 42, 33, 64, 29, 37, 44];- Write a
forloop that will iterate through thestudentReportarray and print to the console the current array value if it is below 30. - Repeat the previous programming snippet by using a
whileloop. - Repeat the previous programming snippet by using a
forEachloop. - Repeat the previous programming snippet by using a
for...inloop. - Use any type of repetition (looping) statement to dynamically produce the day names (Monday, Tuesday, Wednesday, etc.) of the next number of DAYS from today's date.
Example Answers
These answers are certainly not exhaustive.
// for loop for (let i = 0; i < studentReport.length; i++) { if (studentReport[i] < LIMIT) { console.log(studentReport[i]); } } // while loop let i = 0; while (i < studentReport.length) { if (studentReport[i] < LIMIT) { console.log(studentReport[i]); } i++; } // forEach loop studentReport.forEach(function (item) { if (item < LIMIT) { console.log(item); } }); // for...in loop for (let i in studentReport) { if (studentReport[i] < LIMIT) { console.log(studentReport[i]); } }Use this CodePen to guide you in a solution to the last question. This requires you to sift through the example code to find what is applicable.
⚙️ CodePen: JavaScript - Get Future Days from Today - Write a