I have an array of objects defined as such:
const people = [
{
name: "John",
dateOfBirth: 1990,
dateOfDeath: 2020
},
{
name: "Jane",
dateOfBirth: 1970,
dateOfDeath: 2019,
},
{
name: "Micheal",
dateOfBirth: 2002,
}
]
I want to loop through the whole array and set the dateOfDeath for every person still alive to today.
I used
people.forEach ( element => {
if(!("dateOfDeath" in element))
element.dateOfDeath = (new date()).getFullYear();
});
My question is, why does this work? how can the callback arrow function access the array element and modify it? shouldn't it modify only the local element variable (which is the function parameter), hence leaving the array item intact?
CodePudding user response:
Because they both have the same reference in the memory, as the object is a reference type.
For more resources about reference type and primitive type.
primitive-vs-reference-data-types-in-javascript.
CodePudding user response:
My question is, why does this work? how can the callback arrow function access the array element and modify it? shouldn't it modify only the local element variable (which is the function parameter), hence leaving the array item intact?
It works because the element
which you receive, you can think of it as a reference to the original item (it works also because object has reference type, you wouldn't be able to do same with primitive types). Like a pointer in languages like C, C . So when you do element.something
you are actually accessing the original item, via the reference.
CodePudding user response:
As a people in this case an instance of Array constructor in js. any array has its own methods, like forEach, map, filter, and others. these methods enable you to loop through the array with reference to its elements(element in this case). so in this case element is a reference (pointer) to the object in the array so you can modify the object throw that reference.
read more about forEach in js: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
read more about references in js: https://flexiple.com/javascript-pass-by-reference-or-value/
CodePudding user response:
Actually the "element" passes in the callback has the same reference as the object. In layman terms both variables pointing same location in heap when you use element.dateOfDeath (It demonstrates that go the location which is pointing by element and there change the dateOFDeath). In normal case when you have normal array of numbers or strings this will not work out because in that case element act as a copy of original item present in array.