0

in the following code snippet, a "for of" iterates over an array and adds 1 to each element in the array.

Why doesn't that transformation persist? When the second "for of" iterates over the same array, none of the elements reflect the transformation performed in the first "for of"

Thank you

let iterable = [10, 20, 30];

for (let value of iterable) {
  value += 1;
  console.log(value);
}

for (let val of iterable) {
  console.log(val);
}
bresson
  • 831
  • 11
  • 20
  • 3
    because you are not updating the index of the array, you are just working on the value. https://stackoverflow.com/questions/12482961/is-it-possible-to-change-values-of-the-array-when-doing-foreach-in-javascript – epascarello Apr 02 '18 at 19:22
  • Because you only assign to the local `value` variable, not the array property. (Hint: not all iterables can even be updated). – Bergi Apr 02 '18 at 19:25

3 Answers3

3

Because you just get the copy of the value and change that copy - the actual item is not changed. If you have an array of primitive types, you need access via the index and update according to that index.

In the for of loop you can get the index and value via entries function, destruct them in the loop for more comfort, change the value and again assign it to the index-th item of the array.

let iterable = [10, 20, 30];

for (let [index, value] of iterable.entries()) {
  value += 1;
  iterable[index] = value;
}

for (let val of iterable) {
  console.log(val);
}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

for of copies the value to the variable specified. You then change that variable.

If you were dealing with an object, then the variable and original array would both hold a value that was a reference to the object.

… but you are not. Numbers are primitives and primitives are immutable.

You could use for in to get the property name and then change what the array holds for that property:

for (let index in iterable) {
    iterable[index] += 1
}

You could use a map to create a new array with different values:

iterable = iterable.map(value => value + 1);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

The for of is only initializing the variable value with an element from that array, in this case with a number which is primitive and primitive are immutable.

So, what you really did was increment that variable value and nothing else.

This is what you need to do to get it work:

let iterable = [10, 20, 30];

for(let [index] of Object.entries(iterable)) iterable[index]++;
//      ^
//      |
//      +--- The function Object.entries returns an 
//           two indexes array, ie [0, 10], [1, 20] 
//           and so on.  This is called destructuring 
//           assignment.

for (let val of iterable) console.log(val);

Or, using a for-loop:

let iterable = [10, 20, 30];

for(var index = 0; index < iterable.length; index++) iterable[index]++;

for (let val of iterable) console.log(val);
Ele
  • 33,468
  • 7
  • 37
  • 75