Home > front end >  I don't know where forEach() works [duplicate]
I don't know where forEach() works [duplicate]

Time:09-21

Guys i am sorry to ask this. Maybe a easy one but i am new at this language.

let arr =[1,2,3,4,5,6];
arr.forEach(a => a  );
console.log(arr);

why doesn't this work?

let arr =[
{name:"a"},
{name:"b"},
{name:"c"}
];
arr.forEach(a => a.name = "d");
console.log(arr);

but this works?

CodePudding user response:

The value passed to the .forEach callback is either passed by value (if it's a primitive type), or effectively as a reference (if it's an object or array).

Your primitive a therefore is modifying a copy of the value, and so does nothing useful. When you pass an object, though, it's possible to modify the properties of that object, because the (copy of the) reference you're now holding in a still refers to the original object.

CodePudding user response:

For each is just a function that loops over the array, by doing a => a , you are not checking for any condition or having any logic there. From my understanding what you looking for in .map function, which loops over an array and returns another one

  • Related