DEV Community

Cover image for Arrays and Loops
Teresa Holfeld
Teresa Holfeld

Posted on

Arrays and Loops

One of the reasons why humans created computers is that they will do hideous, repetitive tasks without complaining. They can process tons of data where we as humans would die of boredom for doing the same thing over and over again.

Imagine that you are an employee of a very successful software business. The software you sell has about 10,000 customers, and they all pay a yearly subscription fee for the software licence. Now your boss, for economic reasons, decides that the company will switch to a different bank account. Your job now is to notify each and every customer about this by email. Bummer.

Imagine you had to do that by hand: go through the list of 10,000 customers and email each about that change. You would probably quit your job. 😅 Fortunately, you can use programming languages for exactly this type of tedious task. In repetitions (or loops, as we call them) lies the true power of programming.

In this article, I won’t show you how you can email 10,000 people automatically (mind you!), but I will show you how to use JavaScript to handle data in the form of lists (i.e. arrays). You will learn how to create arrays, how to access them, and how to iterate through them. This is one of the most important concepts that you need to learn in order to become a programmer.

All examples of this blog post are published here. For the best learning experience I encourage you to create your own Repl on repl.it and try all steps yourself.

Doing the same thing over and over again: Loops

Bart Simpson

Let’s say, your task was to write the words “I will use loops for repetitions” and print it out on the console 20 times. How would you go about that? You could of course write 20 of these lines:

console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
console.log("I will use loops for repetitions")
Enter fullscreen mode Exit fullscreen mode

With copy-and-paste this is doable. But you guessed correctly: there’s an easier way to do it.

JavaScript has a so-called for loop that is exactly made for this type of repetitive task. You can use it to repeat a task for a certain number of times.

In our example, a for loop would look like this:

for (var i = 0; i < 20; i++) {
  console.log("I will use loops for repetitions")
}
Enter fullscreen mode Exit fullscreen mode

Much nicer, isn’t it? Short and concise. 😊

You need to write the line that is repeated only once, and the repetition is done automatically.

Let’s dissect the for loop and understand all of its parts.

for (...) {
  ...
}
Enter fullscreen mode Exit fullscreen mode

The for keyword signals the program: this is a loop—do this for … repetitions.

Everything that goes inside the curly brackets {} will be repeated.

var i = 0;
Enter fullscreen mode Exit fullscreen mode

Here we create a variable i. This is a helper variable.

It is usually called i because it is the variable for the index.

With every time the loop is repeated, i will increase.

Note: i starts at 0, not at 1. In programming, we always start counting at 0. We will talk about this in more detail a little later.

i < 20;
Enter fullscreen mode Exit fullscreen mode

This statement says: repeat as long as i is less than 20.

We will see what this means when we look at the next statement:

i++
Enter fullscreen mode Exit fullscreen mode

This means: increment (increase) i by one. It is the same as saying i = i + 1.

📝 For your cheat sheet:

i++ is the same as i = i + 1.

Knowing this, we can now have another look at the complete for statement:

for (var i = 0; i < 20; i++) { ...
Enter fullscreen mode Exit fullscreen mode

So the whole statement is saying:

  • First, create a variable i which should have an initial value of 0.
  • Then the loop should repeat as long as i < 20.
  • And for each iteration, i gets incremented by 1: i++.

So in the first iteration, i is 0, in the second iteration it is 1, in the third iteration it is 2 and so on, and it stops if the condition i < 20 is not fulfilled anymore. Meaning: if i is 20 it stops executing.

To make this visible, we can modify the console log a bit and also print out i:

for (var i = 0; i < 20; i++) {
  console.log("I will use loops for repetitions " + i)
}
Enter fullscreen mode Exit fullscreen mode

This now prints:

I will use loops for repetitions 0
I will use loops for repetitions 1
I will use loops for repetitions 2
I will use loops for repetitions 3
I will use loops for repetitions 4
I will use loops for repetitions 5
I will use loops for repetitions 6
I will use loops for repetitions 7
I will use loops for repetitions 8
I will use loops for repetitions 9
I will use loops for repetitions 10
I will use loops for repetitions 11
I will use loops for repetitions 12
I will use loops for repetitions 13
I will use loops for repetitions 14
I will use loops for repetitions 15
I will use loops for repetitions 16
I will use loops for repetitions 17
I will use loops for repetitions 18
I will use loops for repetitions 19
Enter fullscreen mode Exit fullscreen mode

You can see here that for every repetition, or iteration, as we call it, i is incremented, and it stops just before i is 20.

💡 In programming, a repeated execution in a loop is called an iteration.

Go ahead and play around with the numbers in your program.

👩‍💻 As an exercise, try printing out the numbers from 1 to 100. (Careful, there’s a little caveat here!) You can see the solution here.

Loops are not necessarily about numbers. You usually want to iterate through other data, like a list of strings or similar.

Let’s have a look at a different example then: we have a list of names and want to print them all out. For that we need an array.

Storing Data in a List: Arrays

In my previous article we had a look at the different data types that JavaScript provides you with. In addition to integer, string, boolean and so on JavaScript has another data type that lets you save lists of data: the array.

An array is basically a list of values. While we said you can imagine a variable like a box that has something inside, you can imagine an array as a shelf with a number of compartments that have something inside.

Array

This is an array of strings. You can see it as a variable that stores a number of string values.

In JavaScript you would create an array like this:

var greetings = [ "Hi", "Hey", "Hola", "Moin", "Hello" ];
Enter fullscreen mode Exit fullscreen mode

Let’s look at another example.

We want to save a list of names, so we could do it like this:

var names = [ "Teresa", "Eva", "Jonas", "Helder", "Clemens" ];
Enter fullscreen mode Exit fullscreen mode

This will create an array of 5 elements: the 5 string values "Teresa", "Eva", "Jonas", "Helder" and "Clemens". The array is saved in a variable called names – this is now the name of the array that we can use to get its content.

For getting one particular name, we need to use the array name and the index, like:

console.log(names[2])
Enter fullscreen mode Exit fullscreen mode

What is the index? The index is the position of the element in the array.

You can try out what happens if you use it like this. What is the output? (It should be “Jonas”). Also try putting in other numbers and see what happens. Do you get how it works?

☝️ Beware: indices start at 0!

One thing that is very important to remember: the indices of arrays start at 0. This means the first is 0, the second is 1, the third is 2 and so on.

Indices

This is how things work in the world of programming. 🤷‍♀️ It’s called: zero-based numbering, if you want to look it up. It’s so peculiar to non-programmers that this is the source of many jokes and memes, like this:

Three programmers walk into a bar

Let’s get back to our array with the names in it and print out each name using its index:

console.log("Name 1:", names[0]);
console.log("Name 2:", names[1]);
console.log("Name 3:", names[2]);
console.log("Name 4:", names[3]);
console.log("Name 5:", names[4]);
Enter fullscreen mode Exit fullscreen mode

This should give you an output like this:

Name 1: Teresa
Name 2: Eva
Name 3: Jonas
Name 4: Helder
Name 5: Clemens
Enter fullscreen mode Exit fullscreen mode

You see here that for the first element we use the index 0, for the second index 1 and so on. I’m sure you get it by now. 😉

Now what happens if you try to access an array element at a position that doesn’t exist? Let’s say at position 19? Let’s try it out!

console.log(names[19]);
Enter fullscreen mode Exit fullscreen mode

This gives us this as an output:

undefined
Enter fullscreen mode Exit fullscreen mode

No wonder, right? The array has only 5 elements, the last of which has the index 4. So the element at index 19 (the 20th element) is undefined.

To practice this and make it more clear, let’s create an array of integers, that hold the numbers 15, 3, 28, 2, 6, 17, 3, 29, 8, 9, 0, 10, 31, 5, 4.

var numbers = [15, 3, 28, 2, 6, 17, 3, 29, 8, 9, 0, 10, 31, 5, 4];
Enter fullscreen mode Exit fullscreen mode

💡 Arrays can hold any data type.

(It can also be mixed, but we won’t look at that now.)

And now we want to print all values.

We know how to access elements in an array now: with the array name and the brackets [] with the index inside. Let’s do it!

console.log("Number 1:", numbers[0]);
console.log("Number 2:", numbers[1]);
console.log("Number 3:", numbers[2]);
console.log("Number 4:", numbers[3]);
console.log("Number 5:", numbers[4]);
console.log("Number 6:", numbers[5]);
console.log("Number 7:", numbers[6]);
console.log("Number 8:", numbers[7]);
console.log("Number 9:", numbers[8]);
console.log("Number 10:", numbers[9]);
console.log("Number 11:", numbers[10]);
console.log("Number 12:", numbers[11]);
console.log("Number 13:", numbers[12]);
console.log("Number 14:", numbers[13]);
console.log("Number 15:", numbers[14]);
Enter fullscreen mode Exit fullscreen mode

This should give us an output like this:

Number 1: 15
Number 2: 3
Number 3: 28
Number 4: 2
Number 5: 6
Number 6: 17
Number 7: 3
Number 8: 29
Number 9: 8
Number 10: 9
Number 11: 0
Number 12: 10
Number 13: 31
Number 14: 5
Number 15: 4
Enter fullscreen mode Exit fullscreen mode

Fair enough, I use the index to access a number in the numbers array like numbers[index] and I get the number.

But now we have a tedious task: We have 15 lines of code that are all very similar. And you guessed completely right: we can use loops here to make this simpler!

Looping Through Arrays

As you remember from above, for loops look like this:

for (var i = 0; i < 20; i++) {
  // do something
}
Enter fullscreen mode Exit fullscreen mode

Here we repeat the loop 20 times. We use i as our index, and go from 0 to 19 (we repeat the loop as long as the condition i < 20 is met), and increment i by one (i++) for every iteration.

Now we could use i here as the index for accessing our numbers array, like numbers[i].

Let’s try that!

for (var i = 0; i < 20; i++) {
  console.log(numbers[i]);
}
Enter fullscreen mode Exit fullscreen mode

Ok, so what exactly are we doing here?

We have a for loop, where we use i as a variable for the index.

In the first iteration, i is 0. So the console.log is called like: console.log(numbers[0]);

And numbers[0] gives us 15.

In the next iteration, i is 1. So it’s like using numbers[1]. And it prints 3 - the value at position 1 (the second value) of the array.

In the next iteration, i is 2, so it’s like using numbers[2]. This gives us 28, because this is the element at index 2.

And so it goes iteration by iteration until it stops after i was 19.

The loop should give you an output like:

15
3
28
2
6
17
3
29
8
9
0
10
31
5
4
undefined
undefined
undefined
undefined
undefined
Enter fullscreen mode Exit fullscreen mode

Hold on, why does it print five times undefined in the end? 🧐

You see, we said that the loop should repeat until i < 20. So it also calls numbers[15], numbers[16] and so on until numbers[19]. And since our array has only 15 elements (the last index is 14), these values are undefined.

But there is a way to loop through an array and avoid running outside of the array and having accidental undefined values.

In JavaScript, you can get the length of an array in this way:

numbers.length
Enter fullscreen mode Exit fullscreen mode

If you put this in console.log() this will give you: 15. Because we have 15 elements in the array. Unlike the index, this count starts at 1, just as you are used to counting. 😉

Count von Count counts

Remember: you can get the length of an array by using the array name, then a dot, and then length. For our other array, names, this would be names.length.

So how does this numbers.length help us with our loop?

We can put it there instead of the 20:

for (var i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}
Enter fullscreen mode Exit fullscreen mode

This gives us the output:

15
3
28
2
6
17
3
29
8
9
0
10
31
5
4
Enter fullscreen mode Exit fullscreen mode

This stops right after the last element, because numbers.length is the limit where we want to stop. This way we have no unwanted undefined values anymore. 🎉

This is common practice for iterating through arrays. Make sure you put that into your notes.

This way of looping through an array also has another advantage: We can add elements to our array, and it will still work.

Try this:

numbers.push(25);
Enter fullscreen mode Exit fullscreen mode

This will add a number 25 to the numbers array at the end of the array.

You use the array name, a dot, and then push, brackets () and inside you put the element to add to the array: arrayname.push(element), generally speaking.

Now our element has a new value at index 15: console.log(numbers[15]) is now giving you 25 instead of undefined. And if we wanted to iterate through our array again, we could do that just as before, no changes:

for (var i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}
Enter fullscreen mode Exit fullscreen mode

This should give us the output:

15
3
28
2
6
17
3
29
8
9
0
10
31
5
4
25
Enter fullscreen mode Exit fullscreen mode

Cool! It included the new element at index 15. 😁

Doing the same, just differently: While Loops

There is also a different kind of loop, the while loop:

var counter = 0;
while (counter < 12) {
  counter++;
  console.log(counter);
}
Enter fullscreen mode Exit fullscreen mode

The while loop is a bit of a minimized version of the for loop. It executes whatever is in the curly brackets {} as long as the condition is met, in this case counter < 12.

The programmer has to do the work of creating the variable (counter), and incrementing the variable (counter++, you remember: it’s the same as saying counter = counter + 1).

While loops are usually used for different use cases, and used much less than for loops. You can for now stick with for loops. But with this, you will also recognize what a while loop is if you see one.

If you are courageous enough, you can try to replace the for loop from above (that loops through the list of numbers) with a while loop. Can you do it?


If you made it until here: congratulations! You now know how to use arrays and loops. This is a huge step in your journey to becoming a programmer!

As always, remember: skill comes with practice. Understanding loops can be a mind-bending experience if you see them for the first time. But every time you create a new loop and use it to iterate through an array, it will get easier. Until one day it’s become so natural that you don’t even need to think about it anymore.

To get you started in this direction, you can practice with an exercise: create an array of integers, say, the age of your closest 10 friends or family members. Loop through this array and print each age with console.log(), but when you do that, add a 😀 if the number is even, and a 🤨 if the number is odd.

Remember: You can find out if a number is even (i.e. divisible by 2) by using the modulo % operator.

You can look up the solution here.

Thanks for reading! If you liked it, press the heart ❤️ or the unicorn 🦄 and share it with your friends. If you got stuck somewhere, leave a comment. I’m a coding school teacher, and I'm always happy to help you learn! 😊

Latest comments (0)