Have you learned about classes, yet? That is how a function call without an argument is possible. It has an execution context with a method. .forEach()
is a method of the Array
class. All instances of arrays have this method in their prototype chain.
We can learn about all the methods inherited by a class instance if it is built in. For instance MDN will have an Array
page that details all the available methods (and properties) for this class of object.
Ever wonder why an object has no length? Because Object doesn’t inherit that property, and it is pointless to have a class method for something so trivial to objects represented as associative arrays. The Object.keys() method returns an array, which does have a .length
property. Arrays and Strings have a length property they inherited from, drum roll, Object.prototype
.
const nums = [
'zero',
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten'
]
We have an array, and we know that an array instance inherits the forEach()
method from its parent class’s prototype.
nums.forEach(function(x, i, a) {
a[i] = x.toUpperCase();
}
> console.log(nums)
['ZERO', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE', 'TEN']
<- undefined
Array.forEach()
doesn’t need to return anything because it is able to execute directly upon the object (in place). That’s why we give it a callback function as an argument so it knows how we want the object manipulated or mutated.
// value local name for `nums`
// \ |
nums.forEach(function(x, i, a) {})
// /
// index
Array.forEach()
scans the entire array. It does not allow ‘break
’. The iterator callback function has three parameters in the above example. One for the value, one to point to the index of that value, and one to give the context array a local name. It is because we have this third parameter that we have a pipeline back to the context object.
Erm, what was the question?