2

How to I change the object in the array with For-of loop? Following code:

let arr = ['a', 'b', 'c', 'd', 'e'];

for (let v of arr) {
    if (v === 'c')  {
      v = 'f';
      break;
    }       
}

console.log(arr);

I want to find the first letter c and change it to an f, but arr doesn't get changed, probably because it is not referenced ? But shouldn't the v of arr make that the object v is the same as the one in arr ?

5
  • 1
    No, JavaScript doesn't allow aliasing of properties. The variable v is a copy of the value in the array.
    – Pointy
    Commented Mar 1, 2016 at 15:53
  • 1
    To do what you want, you could use .map(), or use .findIndex() to find the target element's index and then modify the array.
    – Pointy
    Commented Mar 1, 2016 at 15:54
  • for in loop over an array is a bad idea. Use built in Array methods to loop over the array! Commented Mar 1, 2016 at 15:54
  • 2
    @epascarello coffee time :)
    – Pointy
    Commented Mar 1, 2016 at 15:54
  • @Pointy Ah, read that as in not of. lol Still see of as a bad choice when you have forEach/filter/map/etc Commented Mar 1, 2016 at 15:56

5 Answers 5

6

v is not a reference to the array element, it's just a variable that is assigned the value that the array iterator yields. If you assign to it, only the variable v changes but not the array.

To do that, you need to explicitly reference the property with its index and assign to it:

let arr = ['a', 'b', 'c', 'd', 'e'];
for (let [i, v] of arr.entries()) {
    if (v === 'c')  {
      arr[i] = 'f';
      break;
    }       
}
console.log(arr); // ['a', 'b', 'f', 'd', 'e']

An iterator does not provide a way to mutate the underlying structure, you need to do it yourself.

2
  • It logs: [ "a", "b", "c", "d", "e" ]. Why?
    – vrintle
    Commented Oct 5, 2018 at 11:28
  • @rv7 I had mixed up index and value from .entries(). Thanks for the heads up!
    – Bergi
    Commented Oct 5, 2018 at 11:33
5

Javascript does not create references to simple values such String. To get array referrenced, you need to let array be an array of objects like [{char : 'a'}, {char : 'b'}, ...]. Then in your iterator you can change elements of array through changing of the char property

let arr = [{char: 'a'}, {char :'b'}, ...];

for (let v of arr) {
    if (v.char === 'c')  {
      v.char = 'f';
      break;
    }       
}
5
  • Ok, understand. What if the array does not contain Strings, but a Custom object with properties? Can I then just change the whole object like v = newObject ? or do I have to v.myProp = newObject.myProp?
    – williamwmy
    Commented Mar 1, 2016 at 16:12
  • @williamwmy I don't sure, but I think that only v.myProp = newObject.myProp possible
    – MysterX
    Commented Mar 1, 2016 at 16:16
  • 1
    @williamwmy Technically v contains just a reference to array element, so v = newObj will place to v a new reference, and old reference to array element will be destroyed
    – MysterX
    Commented Mar 1, 2016 at 16:18
  • thanks, I tried, and you are right, I cant just set the whole object, and since the object has tons of properties, I have to loop through them too which makes the code a bit messy.
    – williamwmy
    Commented Mar 1, 2016 at 16:19
  • @williamwmy, you can place to array [{obj : yourObjectWithTonsOfProperties}] and then v.obj = newObj
    – MysterX
    Commented Mar 1, 2016 at 16:20
2

As detailed in the MDN spec, let is declaring a new variable from a copy of your array element. So changing the v will not change the value in the array. This is shared by var and const and is simply just javascripts behaviour. When you create a new object, it starts empty.

Your loop is basically saying "For every element in arr, declare a variable holding a copy of it and then if that variable is c, change that copy to f"

4
  • 1
    The behavior has nothing to do with let. You would see the same with var. Commented Mar 2, 2016 at 5:18
  • I never said Let was the problem, but that it's behaviour would cause what is happening
    – millerbr
    Commented Mar 2, 2016 at 7:51
  • But the same can be said about var or const. The behavior is by no means specific to let, it's simply how values work in JS in general. Commented Mar 2, 2016 at 14:31
  • Thats true and a fair point and, although I never said it was specific, I'll take your advice and mention that it isn't let specifically causing the problem
    – millerbr
    Commented Mar 2, 2016 at 14:41
1

Before you change v both, the array and v point to - or in this case have - the same value:

arr[2] -> 'c' <- v

After you change v it has a different value, but you didn't change the array:

arr[2] -> 'c'  v -> 'f'

v and arr[2] are only placeholders, but different ones.

0

The correct answer:

let arr = ['a', 'b', 'c', 'd', 'e'];

let i = 0;
for (let v of arr) {
  if (v == 'c')  {
    arr[i] = 'f';
    break;
  }
  i++;
}
console.log(arr);

:-P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.