What is a loop?
Video outline
In computer science, a loop is a programming structure that repeats a set of instructions until a specific condition is met or until the end of the loop is reached (It’s like going through your shopping list until you’ve collected every item from it). Programmers use loops to iterate through values, add sums of numbers, repeat functions, and many other things.
The most common type of loop is the For Loop which ** has two parts: a header specifying the iteration, and a body which is executed once per iteration.
Let’s say I want to print the phrase “I like learning liquid” 3 times in my code. I could do something like this:
{{ "I like learning liquid" }}
{{ "I like learning liquid" }}
{{ "I like learning liquid" }}
But what if I want to print that phrase 1,000 times instead? Then the above is not efficient.
Instead, I can use a loop. The code below will print the phrase “I like learning liquid” 3 times:
{% for item in (1..3) %}
I like learning liquid
{% endfor %}
All loops have a stopping condition. The loop will continue to run until a certain condition is reached (in the above example the loop stops after the 3rd iteration)
Loops are commonly used in programming because they save time, reduce error, and are easy to read simply because the instructions are written just once by the programmer whilst the computer will execute them multiple times.
Updated over 3 years ago