Iterating over objects and arrays

Iterating over objects and arrays

Looping over arrays in javascript let's say its easier than before, or at least there are more options now than the "old" for loop even that its still pretty helpfull.

This article as it will be more focused on arrays and objects I will not focus on all the array looping methods.


So if you have an array a easy way to loop it is with `for...of`


const animals = \['lion', 'leopard', 'panda', 'koala', 'camel']

for (const animal of animals) {

If you wonder how it works, I try to keep it simple. The syntax is:

for (variable of iterable)

In the variable you put wathever you want, normally as an array would be a plural of things, you put the singular. So in this case, the array name is animals and the variable is animal. The iterable is going to be the array name for...of you don't create a new array, neither you change the array that exists. So here the animals array will continue to be as it was.

So if you want to only get the first letter of each animal name you can do it with for...of but still would not change the array.

for (let firstLetter of animals) {
    firstLetter = firstLetter.charAt(0)
    console.log(typeof firstLetter) //string


With map is a different story, you will create a new array.

So with the same array that we had I want to and