Inventors - Iterations Lesson
Categories: JavaScriptThis is the lesson for iterations in JavaScript.
- Presented by the Inventors
Iterations
Iterations allow you to execute a block of code multiple times. It helps you automate repetitive tasks and consists of the following components.
Repetition
Repetition means that a block of code is executed multiple times instead of writing it out manually for each occurrence. This is usually achieved with loops such as for, while, or do-while loops.
Why it’s useful: Saves time and avoids redundancy. Instead of writing 100 lines to print numbers 1 to 100, a loop can handle it in just a few lines.
Makes programs easier to find if tomorrow you need 1,000 repetitions instead of 100, you just adjust a single parameter. Easier to update.
Condition
A condition decides when a repetition should stop or continue. Things like loops tend to rely on conditions to decide whether another cycle should run. Why it’s useful:
Conditions are useful because it ensures that repetitions won’t be infinite. Conditions also allow you to use efficient resources by stopping the execution after Allows efficient resource use by stopping execution once a goal is reached (e.g., halting a search once the answer is found instead of checking every possibility).
Progress
Progress describes the change that happens during each iteration or each loop. With the progress the condition changes and without it it leads to an infinite loop. Progress is achieved most of the time by updating variables or processing data. Why it’s useful: It makes it go closer and closer to the desired output.
Helps solve complex problems step by step, good examples of it would be improving numerical approximation.
It creates the basis when you need algorithms to solve problems involving searching or sorting.
Snake Game
Lets see how iterations are used in the Snake game:
%%javascript
//Examples of iterations in snake:
for (let i = 0; i < wall_setting.length; i++) {
wall_setting[i].addEventListener("click", function() { ... });
}
//This is one example of iteration from the snake game.This loop iterates over every element in wall_setting. The purpose is to attach a click event listener to each element. Without iteration, you’d have to manually write an event listener for each one.
for (let i = 0; i < wall_setting.length; i++) {
if (wall_setting[i].checked) {
setWall(wall_setting[i].value);
}
}
//This loop runs every time someone clicks
//The Purpose is to find which one is checked, then use its values
Let’s take an example of a guessing game
Repetition: The program keeps asking for guesses.
Condition: The loop continues until the user guesses correctly.
Progress: Each guess is compared to the last one, and the computer also gives hints like “too high” or “too low”.