Why this behavior in a forEach loop?

var arr = ['hello','house','human']
var name = 'John';
arr.forEach(function(item,i,arr){
 item = name;
})
console.log(arr); //['hello','house','human']

the code above will print ['hello','house','human']
but if instead the item to write arr[i] , then everything works as it should and displays ["John", "John", "John"]
var arr = ['hello','house','human']
var name = 'John';
arr.forEach(function(item,i,arr){
 arr[i] = name;
})
console.log(arr); //["John", "John", "John"]

why? in fact item == arr[i], but it works not as it should be
June 5th 19 at 21:10
4 answers
June 5th 19 at 21:12
Solution
item - the variable that is passed by value.
arr - an array passed by reference.
June 5th 19 at 21:14
Solution
item is a variable function forEach. In each iteration this variable is set to the value in the array. You overwrites it with its (the function variable). After the function has fulfilled its variables cease to exist, the array is unchanged.
June 5th 19 at 21:16
It all depends on the implementation of native functions and as I understand every engine the implementation may have its own.
In principle, the documentation does not say anywhere that the item is a link to a specific element of the array, that is, it can be only argument-values, and no more, i.e. it overwrites the overwriting you're only argument/local variable, not an array element directly.
June 5th 19 at 21:18
If I write so
var arr = [{name:'hello'},{name:'house'},{name:'human'}]
var name = 'John';
arr.forEach(function(item,i,arr){
 item.name = name;
})
console.log(arr);

Then
(3) [{...}, {...}, {...}]
{name: "John"},
{name: "John"},
{name: "John"}

The item is the value of the item and not the item itself, wrap the value in an object as in the example above, then the item will be referenced, and so it is only a copy of the value, so the change will be a copy, not the item itself.

Find more questions by tags JavaScript