Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  28] [ 6]  / answers: 1 / hits: 16345  / 10 Years ago, fri, may 30, 2014, 12:00:00
var arr = ['Foo'];

arr.forEach(function(item){
console.log(item);
item = 'Lorem';
console.dir(arr[0]);

});

for (var item in arr){
arr[item] = 'Ipsum';
console.dir(arr[0]);
}


Like the code above shows, I noticed that changing the value of an item passed to the callback of forEach() does not cause the iterated object to alter.



Using for...in certainly does.



Why is that & how should I alter values in an array?



I find that the topic is covered quite confusing on MDN


More From » foreach

 Answers
8

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';

[#70781] Thursday, May 29, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
viridianaw

Total Points: 154
Total Questions: 94
Total Answers: 89

Location: South Georgia
Member since Sun, Aug 8, 2021
3 Years ago
;