0

I expected the first console.log to be [0,10,20,30] and the second to be [0,100,20,30]:

var arr = [0,10,20,30]
console.log(arr)
arr.forEach(each)
console.log(arr)

function each(data,index) {
   if (index === 1) {
      data = 100 // This isn't assigned to arr[1]
   }
}
Phillip Senn
  • 46,771
  • 90
  • 257
  • 373
  • arr[index] = 100. You can't assign to an array's index without the array. – Denys Séguret Mar 06 '17 at 15:13
  • Regardless weather it's forEach or any function this can never happen in javascript because it never pass by reference: http://stackoverflow.com/questions/13506398/why-are-objects-values-captured-inside-function-calls/13508654#13508654 – slebetman Mar 06 '17 at 15:15
  • `forEach` doesn't do the change inline. You have to use map for achieve that. – kvn Mar 06 '17 at 15:17

1 Answers1

2

You are assigning a value to a local variable. For assigning to the actual index, you need the array and the index, the parameter two and three of the callback API of Array#forEach

var arr = [0,10,20,30]
console.log(arr)
arr.forEach(each)
console.log(arr)

function each(data,index, array) {
   if (index === 1) {
      array[index] = 100;
   }
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392