Loops
We often use computers to perform repetitive tasks quickly and efficiently. And this is what loops are for: to iterate!
Let’s set things up for this lesson.
Make a new folder somewhere on your computer, open it with VS Code, and create two files:
main.ts
, where we will write our code. To start, you can addconsole.log("Hello!");
to it.deno.json
, which lets VS Code know this is a Deno project and enables the Deno extension. You can tweak settings in this file, but we’ll keep it empty for now.
Open the terminal and run the following command: deno run --watch --check main.ts
This command clears the terminal and reruns main.ts
every time you save it (CMD
+ S
on Mac or CTRL
+ S
on PC).
You can use this setup to test the code provided in this lesson.
With arrays
Let’s say we have ten numbers (1 to 10), and we want to multiply each of them by 2 and log the results.
We could write this code:
console.log(1, "=>", 1 * 2);
console.log(2, "=>", 2 * 2);
console.log(3, "=>", 3 * 2);
console.log(4, "=>", 4 * 2);
console.log(5, "=>", 5 * 2);
console.log(6, "=>", 6 * 2);
console.log(7, "=>", 7 * 2);
console.log(8, "=>", 8 * 2);
console.log(9, "=>", 9 * 2);
console.log(10, "=>", 10 * 2);
But it’s pretty repetitive. And what happens if we want to do the same thing but with 100 numbers? Or if we want to multiply by 3 instead of 2? Typing or modifying it all would take a long time!
Instead, you can use… loops and arrays! Arrays are iterable, which means you can use them easily with loops.
To create a loop, you start with for
, followed by the loop parameters between ()
. Then you need to tell the computer what must be done at each iteration inside {}
.
Let’s rewrite our code, but this time with an array and a for
loop.
Here’s what’s happening in the code below, step by step:
- On line 2, we create an array
numbers
. - On line 4, we create a new variable
n
that will store the values fromnumbers
, one by one. - On lines 5 and 6, we instruct the computer to multiply the
n
value by two, store it in a new variable, and log it. The computer will do this for each value innumbers
, one by one.
// Add or remove items in the array and save.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (const n of numbers) {
const multiple = n * 2;
console.log(n, "=>", multiple);
}
If the computer could talk 🤖, here’s what it would say when running this script:
- Line 1: This is just a comment for humans. I ignore it.
- Line 2: Hello
numbers
! Nice to meet you. - Line 3: Nothing. Humans love empty spaces.
- Line 4: Hey, this is a
for
loop. Hellon
! I’ll use you to store each value ofnumbers
, one by one. - Line 5-6: Let’s iterate!
- I put the first value of
numbers
inn
. I multiplyn
by 2 and I log it. - I put the second value of
numbers
inn
. I multiplyn
by 2 and I log it. - […]
- I put the tenth value of
numbers
inn
. I multiplyn
by 2 and I log it.
- I put the first value of
- Line 7: I iterated over all values of
numbers
. I am done! Sayonara! 👋
The beauty of this syntax is that no matter the number of values in numbers
(10, 1,000, or 1,000,000), the code will remain short and straightforward, and you can be confident that all values will be processed.
Also, the actual code for the iterations is contained between the {}
. So, if you need to multiply by 3 instead of 2, you only need to update your code in one place, reducing the risk of missing another spot and introducing bugs.
Regular for
loop
While it’s convenient to loop over an array, you don’t need one to iterate.
If you want to say hello a million times, you can use a regular for
loop, as shown in the code below.
The loop requires three expressions between ()
before running the code inside the following {}
:
- First, you need a variable to store a number. By convention, it’s called
i
, but you can name it anything you want. This variable represents the starting number for the iteration. Here, it’slet i = 0
. - Second, you need a condition to keep the loop running and eventually stop it. This is usually done using comparison operators like
<
or<=
with the variable. Here, it’si < 1_000_000
, meaning the iterations continue whilei
is smaller than1_000_000
. - Lastly, you need to specify how to increment the variable. Here, we use
i++
, which means increment by 1 on each iteration.
These expressions must be separated by ;
within the ()
.
The result is a loop starting with i = 0
and stopping when i
equals 999,999. Because i
increments by 1 on each iteration, this loop iterates 1,000,000 times.
for (let i = 0; i < 1_000_000; i++) {
console.log(i, "Hello!");
}
You just asked your computer to do something A MILLION TIMES! And with just 3 lines of code! Do you feel the POWER in your hands? 😈
You can play with the expressions. For example, try making these changes and see what happens:
- Replace
let i = 0
withlet i = 1000
- Replace
i < 1_000_000
withi <= 1_100
- Replace
i++
withi += 10
break
Sometimes, you might want to stop your loop when a specific condition is met. To do this, you can use the break
statement. It works in any loop.
For example, in the code below, we loop over names
, but we break the loop if one of the names starts with J. Since "Jerry"
meets this condition, it’s the last name being logged.
const names = [
"Tom",
"Ivan",
"Jerry",
"John",
"Smith",
"Derek",
"Stuart",
"Dustin",
"Jenny",
"Jasmine",
];
for (const n of names) {
console.log(n);
if (n.startsWith("J")) {
break;
}
}
Conclusion
Loops are an incredible tool for data analysis. They allow you to iterate quickly and efficiently through massive volumes of data with just a few lines of code.
Note that there are other kinds of loops, like while
loops. However, they are rarely used in a data analysis context.
And now, I think it’s time for our first project! We’ve covered all the basics. Congrats! 🕺