6.9 Iterating an Array

Earlier in the section about control flow you learned about different loops in JavaScript. So in this section, you learned that if you want to iterate an array, you can use the for of loop. So, for, let, number of numbers, now in each iteration, that number will be set to one of the elements of that array. So, let's record this on the console. We get 1, 2 and 3. There is also another way to iterate an array, and you can see this approach in some online Tutorials. It's the for each method. So all these arrays have this for each method. It takes a callback function. So we pass a function here, this function takes a parameter, in this case number, and in this function, we can just record that number on the console. So when the for each method, this function will be executed for each element in the array. Each element will be passed as an argument to this function. So, save the changes, we get 1, 2, 3 again. Now, as I told you before, we can use the arrow function syntax to simplify this code, so we get rid of the function keyword, put an arrow between the parameters and the body of the function, and because we have only one parameter, we can remove the parentheses, and finally we need to remove this semicolon here because we don't have this statement in a block of code. So here's the end result. There's really no significant difference between these two ways of iterating an array. The only thing you need to know is that this call back function, which we pass through the For each method, can optionally take a separate parameter, and that's the index. So here I'm going to put number in parentheses to add the second parameter, which is the index, Now when we log each number or each element, we can also display its index. Save the changes and you can see the index of each element before it. We don't get the index with the for of loop, but if you need it, we can use the for in loop. That's it for this video about iterating an array in JavaScript, let's meet again for a very next video.