13.6 Loop Optimization (10 mins)
// Loop through only half of an array (optimization) for (let i = 0; i < array.length / 2; i++) { console.log(array[i]); }// Bad practice: Length is recalculated every time for (let i = 0; i < array.length; i++) { // Do something } // Optimized: Length is stored once and used repeatedly const length = array.length; for (let i = 0; i < length; i++) { // Do something }// Break early when a match is found for (let i = 0; i < array.length; i++) { if (array[i] === target) { console.log("Found the target!"); break; // No need to continue the loop } }for (let i = 1; i <= 10; i++) { if (i % 2 === 0) { continue; // Skip even numbers } console.log(i); // Outputs: 1, 3, 5, 7, 9 }
Student Activity (10 mins):
Step-by-Step Activity:
Challenge:
Activity Follow-up Questions:
Expected Outcome:
Last updated