_ forEach vs for

Array.prototype.forEach() is a less verbose form of a for of loop.

a = [2, 4, 6, 8, 9, 11, 13, 15]
for (let x of a) {
    console.log(`${x} is ${x % 2 ? `odd` : `even`}`);
}

versus,

const evenOdd = x => {
  console.log(`${x} is ${x % 2 ? `odd` : `even`}`);
}
a.forEach(evenOdd)

Both will output the same thing…

2 is even
4 is even
6 is even
8 is even
9 is odd
11 is odd
13 is odd
15 is odd

The advantage is that rather than having a one-off expression in the for loop, we have a re-usable, standalone function that can be shared with the rest the program. evenOdd() is known as a callback, that might have already come up in lessons, but if not, it will soon in Higher Order Functions.

.forEach() has no return value, and the iteration cycle cannot be broken (terminated with break. A for loop can contain a breaking condition, if needed.

1 Like

This is in the section of C#, for some reason @communitybot did not put a category on that, strange. At least, this is where the link exists.

D’oh! Mistook it as a JavaScript topic. C and JS have very similar syntax so some of the above may still apply, apart from the ES6 template literal.

What’s this:

?
I don’t understand it.

The first example is the imperative form of the logic, a simple for..of loop. In JavaScript, like in Python, we can access an array by index, or by value, depending how the for loop signature line is written.

for (let i = 0; i < a.length; i++) {
    console.log(`index: ${i}, value: ${a[i]}`)
}

The in keyword common to iterating JS objects, is not a valid keyword for iterating arrays, and can exhibit side effects so was always avoided. With the introduction of the, of keyword in ES2015 we finally had a way to access the values directly in their respective elements.

for (let x of a) {
    // x is a value, not an index
}

That’s the procedural side of things. With the new iterations of JS (ECMAScript2015 and beyond) we were also given a set of powerful iterators that would permit us to write declarative code using expressions. Array.forEach() is one such iterator. It is not assigned since it returns nothing, but it is very handy when we want to perform the same or similar task on an entire array’s content, per element.

Array.forEach() is a higher-order function that takes a function as its argument. The function is known as a callback since the iterator calls it back for each value in the array, and that call is the invocation of the function, hence we pass only a reference, if it is a standalone function, or we pass in an anonymous function expression directly as the argument. There is no break, or stopping condition. .forEach means for every in reality.

a.forEach(evenOdd)

depends upon evenOdd(). Below we pass an arrow function expression directly,

a.forEach(x => {
  console.log(`${x} is ${x % 2 ? `odd` : `even`}`);
})

or even the old fashioned way,

a.forEach(function (x) {
  console.log(`${x} is ${x % 2 ? `odd` : `even`}`);
})

Additionally, one might have to do some reading up on the other strange thing in the room, the template literal which is also new to JS (as of 2015) and introduced the back tick as another form of quote mark (valid everywhere in JS) as well as the template for direct interpolation of variables, similar to Python’s f-string.

`${x}`

The template permits us to interpolate x rather than concatenate a string with the variable, which we had to do previous to this new string form.

console.log(x + ' is ' + (x % 2 ? 'odd' : 'even'));

Even something as simple as this can be convoluted with concatenation.

Like in Python, the template can be given any expression, not just a variable. Note where our ternary is sitting… Right inside the template, since a ternary is an expression.