

Note: in the above example, the variable capWords is undefined after execution has completed.I'm just stumbling over a little improvement (syntactic sugar) thatĬould help to make code a bit smaller (-> less to debug, read, This lets us easily apply a set of changes to an entire array! The method is applied to each element in the array in turn, capitalizing each word before updating the contents of the original array. This function can receive any array of words, and will operate similarly on the input. The forEach() method in the example above invokes the capitalize() function. Note: Since every item in the array stands for a word, we changed the name of the item parameter to “ word”. const words = Ĭonst capWords = words.forEach(capitalize) Īrr = word.toUpperCase() + word.substring(1) Read more about this here.īelow is some sample code that uses forEach() to iterate through a list. thisValue allows the this context to be changed.Since forEach() returns undefined, this can be useful if changes to the original array are required (the example below shows this in action) ○ index is the index of the current item in the array being processed

To improve readability, the item is generally named after the type of the object stored in the array (e.g.

It was introduced in ECMAScript 5 (ES5), and is supported in all modern browsers. ForEach() is an iteration method, and it is mainly used for the serial execution of functionality against a list of elements.Īrray forEach() is a method included in the Array.prototype property.
