Does ForEach() Bind By Reference?
Solution 1:
Using for...in certainly does.
No it doesn't. Your forEach
loop is equivalent to this for...in
loop (apart from the order):
for (var index in arr) {
var item = arr[index];
console.log(item);
item = 'Lorem';
console.dir(arr[0]);
}
Do you see that the array isn't modified either? That's because JavaScript is always pass-by-value, and there is a very simple rule to keep in mind:
Assigning a value to a variable never changes the value of another variable or data structure.
That means, assigning a new value to item
, cannot change an element of arr
. If you want to to modify the array, you have to mutate it directly by assigning a value to an index, i.e.
arr[index] = 'foo';
Solution 2:
In your case, the item
variable is passed by value, because it is of a primitive value. If it were a json object, and you would change one of its properties, it would be reflected on the original list.
In this situation, you can use other arguments that the forEach
has. For example:
arr.forEach(element, index, array) {
...
}
Using these arguments, you can affect directly array[index]
Solution 3:
Notice that callback in forEach
gets three arguments. The second one being an index of current element, and the third one the array itself. If you want to modify the array, use these two arguments.
Post a Comment for "Does ForEach() Bind By Reference?"