Join the DZone community and get the full member experience.Join For Free
If you're new to programming, this might be a whole new concept. (If so, welcome! We're excited to have you. For those of you who've seen this more than a few times, feel free to skip to a later section.) In the above code block, we're first creating an array containing a "Hello, World!" message.
Next, we're starting our for-loop. For-loops are defined by two sections, a header, where we specify how the loop will run, and the body, where we define what will happen at each iteration of our loop. The head of a for-loop contains three sections. The first defines a value, often a single letter, like
i, that we want to start indexing our array at. The second defines a condition that will terminate our for-loop. The third performs an operation on
i to move it to the next element in the array.
In this case,
i is 0, our terminating condition is
i < 7 (the length of our array), and we add 1 to
i to move it to the next index in our array. This tells our program that we want to look at each element in our array, starting at 0 (our first index) and ending at 6 (our last index).
You may also like: Iteration Over Java Collections With High Performance.
In the body of our for-loop, we grab the element at
i, assign it to a variable,
currElem, and then print the index and the value of
currElem to the console. Our output for this will be:
Among the many helpful array methods introduced in ES6 is
forEach takes a callback function as a parameter. The callback then takes a variable representing an individual element in an array as a parameter. Inside the body of the callback, we can create custom logic to perform an operation with or on each individual element of the array.
forEach does not return a new array of elements. If you mutate the element within the callback function, every element in the array will be mutated. (Take a look at
map if you're looking to maintain state).
Let's see a simple implementation of the method with an anonymous callback function as our argument:
You can also use a predefined function as the callback, like this:
Both of these implementations will result in a similar output to the one we had with our native for-loop:
If you need the index of the current element in the array, you can just add a second parameter to the callback function, like:
i is the current index of the array, while
elem is the current value at that index.
The syntax here is pretty straightforward. In the first half of the header, we declare a variable that represents an individual element in our array. We then use the
of keyword followed by the array that we want to iterate through: "For every element of this array, do something." (The only implementation that would be more readable would be if
in could replace
- JS Array From an Array-Like Object
Opinions expressed by DZone contributors are their own.