noc-book-2
noc-book-2 copied to clipboard
forEach and for in
Chapter 4 covers for of
loops and also mentions higher order functions like filter()
. I may want to mention the existence of forEach()
and for in
as well which often cause confusion.
Maybe it is worth considering a quick JS primer chapter in the beginning? You're welcome to draw on some of the fundamental concepts outlined here:
- Arrow functions: https://github.com/itp-dwd/2020-spring/blob/master/guides/javascript-frontend-guide.md#arrow-functions
- Array Methods: https://github.com/itp-dwd/2020-spring/blob/master/guides/javascript-frontend-guide.md#javascript-array-methods
I've written a couple extra paragraphs for this chapter on the various for loops!
This final
for
loop demonstrates how to call functions on every element of an array by accessing each index. I initialize a variablei
with a value of 0 and increment it by 1, accessing each element of the array until I reach the end.However, let me take this opportunity to mention the various ways in JavaScript that you can use to iterate over an array. This is one of those things that I both love and hate about about coding in JavaScript—there are so many different styles and options to consider, making it a highly flexible and adaptable language! The flip side is that that the abundance of choice can be overwhelming and lead to a lot of confusion when learning.
Let’s take a ride on the loop-de-loop rollercoaster of choices for iterating over an array:
- The traditional
for
loop: This is what you are probably most used to and follows a similar syntax as other programming languages like Java and C.- The
for...in
loop: This kind of loop allows you to iterate over all the properties of an object. It's not particularly useful for arrays, so I won't cover it here.- The
forEach()
loop: This is a great one, and I encourage you to explore it! It is an example of a "higher-order" function which I will explain later in this chapter.- The
for...of
loop: This is the one I will expand upon below. It provides a clean and concise syntax compared to the traditionalfor
loop when working with arrays of objects.