I've encountered with this piece of code in a book I'm reading, and I couldn't understand what the b argument that is defined in the function inside the forEach method does.
Here's the source code:
var tab = [2, 3, 5];
tab.map(x => x + 3)
.filter(x => x > 5)
.forEach(function(a,b){console.log(a-3);});
Okay, I've dug a bit deeper and found out that the function inside the forEach() method can take up to 3 arguments, so the function can be written like this: forEach(function(a, b, c) { // Instructions }); with a being the element of the current iteration, b being the index of that element and c being the array itself.
Example:
const samples = ['sample_1', 'sample_2', 'sample_3'];
samples.forEach(function(a, b, c){
console.log(a); // shows the element
console.log(b); // shows the index of the element
console.log(c); // shows the whole array
console.log('Onto the next sample.')
});
In this example, on the first iteration, a will be 'sample_1' b will be 0 and c will be the whole array.
Second iteration, a is 'sample_2', b will be 1 and c will be the whole array.
And so on with all the remaining iterations. Note that the function inside the forEach() method takes only 3 arguments, not more.
b is optional, it is the index of the element