Loops are a great tool because they’ll repeat a certain chunk of code without us having to retype it a bunch of times. Overall, it saves a lot of time and screen space. There are three types of loops: the for, while, and do-while loops. For every kind of loop, we have to establish what code we want to repeat (which is the loop) and then create a stopping point for when a certain condition is met. The for loop is commonly used and will keep going until the loop comes back as false. The while loop repeats until the looping condition comes back as false. A do while loop doesn’t execute unless the first set of conditions aren’t met from the start. Going back to the for loop, there are a few important things it needs to function. First, it needs a starting point. This is normally where the code is declared and initialized. Next, it needs a condition. This is basically what tells the loop when it’s going to stop. Finally, the loop needs to have a step. This determines what will happen to the starting point. For example, if it increases by 1, we type in i++. A for loop with all of its key components would look something like this:
for (let i = 0; i < 10; i++) {
saySomething();
}
function saySomething () {
document.writeIn(“hello!”);
}
Leave a Reply
You must be logged in to post a comment.