In coding, you will often see loops. Loops are used basically as a shortcut. It shortens what could be numerous lines of code into just a couple and allows for code to be written once and run as many times as needed. It executes tasks much quicker, saving lots of time. If we want the code to run a specific number of times we use the “for” loop. An example is as follows:
const loopTime = 5;
for (let i = 0; i < loopTime; i++) {
console.log(`Iteration is #${i}`);
}
If we want to run code but do not know the specific number of times we use a “while” loop. This will repeat a certain block of code an unknown amount of times until the condition is met. An example is as follows:
while (i < 10) {
text += “The number is “ + i;
i++;
}
Furthermore, you can also use the “Do While” loop. This variant will execute the code as long as the condition is true, and will repeat if the condition continues to be true. An example is as follows:
do {
// code block to be executed
}
while (condition);
Leave a Reply
You must be logged in to post a comment.