๐ง๐๐ฝ๐ฒ๐ ๐ผ๐ณ ๐๐ผ๐ผ๐ฝ๐ ๐ถ๐ป ๐๐ฆ
Writing repetitive code makes your programs hard to maintain. It increases errors and wastes time. You should follow the DRY principle: Do Not Repeat Yourself.
Loops solve this. They let you run the same code many times with one block of logic.
JavaScript has three main types of loops:
- The While Loop This is an entry-check loop. It checks the condition before it runs the code. If the condition is false at the start, the code never runs.
Use this when you do not know exactly how many times you need to repeat a task. For example, waiting for a user to enter a correct password.
- The For Loop This is also an entry-check loop. It is a compact version of the while loop. It puts the start point, the condition, and the update step in one line.
Use this when you know exactly how many times to run the code. For example, printing numbers from 1 to 100.
- The Do...While Loop This is an exit-check loop. It runs the code first and checks the condition last. This means the code runs at least once, no matter what.
Watch out for infinite loops. An infinite loop happens when your condition never becomes false. This consumes memory and can crash your program. Always ensure your loop has a way to stop.
Key technical notes:
โข Initialization: Where the loop starts. โข Condition: Whether the loop keeps running. โข Increment/Decrement: How the loop updates after each turn. โข Curly Braces: Use these to group multiple lines of code. Without them, only the first line belongs to the loop.
Functions also help you avoid repetition. They act as reusable blocks of code. You define them with parameters and call them with arguments. If you skip an argument, the value becomes undefined.