Reputation: 1787
I have been reading the book **JavaScript: The Definitive Guide, 7th Edition", in this book is included forEach example that I am not able to get it:
let data = [1,2,3,4,5]
data.forEach(function(v, i, a) { a[i] = v + 1; });
console.log(data); //[2,3,4,5,6]
I do not know how the parameters v, i, a
are getting its value from the data array. If I change the order instead of (v, i ,a), then I get different result. Why it has to be in this order (value, index, array)? I have not been able to find why this strict order.
For example, this other snippet is very straighforward:
let sum=0;
data.forEach((value) => {sum+= value;});
each element of data is passed to the body of the arrow function and it is adding the value and storing in sum which adds them up.
Can you please provide insight about the first example?
Thanks
Upvotes: 0
Views: 733
Reputation: 619
Have a look at the syntx of the Array.prototype.forEach()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
There is not much to say about the order, it's just the intended way of using the interface. You could use red, green and yellow for all intends and purposes, but the order would stay the same.
First param will be the element value, second one the index and third the array itself.
let data = [1,2,3,4,5]
data.forEach(function(red, green, yellow) { yellow[green] = red + 1; });
console.log(data); //[2,3,4,5,6]
data.forEach(function(value, index, array) { array[index] = value + 1; });
console.log(data); //[3,4,5,6,7]
In newer versions of JS you could do something like
const array = [ 1, 2, 3, 4]
for (const number of array) {
console.log(number)
}
for (const [number, index] of array.entries()) {
console.log(`${number} has ${index}`)
}
And since the naming of the objects do only matter inside the forEach()
scope, you could simply set them to something that makes sense in the context you are in, so your iteration gets easier to read and understand. E.g.: for (const car of cars) {//car go honk}
See for .entries()
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries
Upvotes: 2
Reputation: 1775
data.forEach funciton need a function as a parameter.
and that function defined as function(value,index,array).you can pass a function with less parameters Eg:function(value),function(value,index).but you can't pass wrong order.
becuase inside the forEach() function.you can image it did like this
//Just for Example.real code not like this
Array.forEach = function(callback){
for(var i in this){
callback(this[i],i,this);
}
}
Upvotes: 0