If you use arrays, you usually have to deal with multiple elements, so it makes sense to combine arrays and loops to iterate over an array. That means we go through every element of an array.
This way, we can easily manage arrays with a dynamic length. That means, at the point where we are writing the code, we don’t know how many elements are inside of an array. It is a common task in programming, and this is why there are special syntax for looping over arrays.
For example, you can get the index of every element inside an array.
1
2
3
4
5
let animals = ["🐹", "🐶", "🐰", "🐱", "🐵", "🦁"];
for (let index in animals) {
console.log(animals[index] + "has the index: " + index);
}
It is a bit easier to read and less to write, as you can see. Of course, you can name the variable inside a loop differently if you like.
If you don’t need the index, there is also a way to get the element directly.
1
2
3
4
5
let animals = ["🐹", "🐶", "🐰", "🐱", "🐵", "🦁"];
for (let animal of animals) {
console.log(animal);
}
You notice that we changed the variable name from index
to animal
to show that this variable will contain the actual object and not the index of the object. Also, the variable name of the array is plural (animals
) while the name of the single element is singular (animal
). This way, you can at first sight see that we deal with a single element or with an array of this elements.