Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Turandeep Munday
Turandeep Munday
6,047 Points

Why can i not increment values in an array using for of even when using let

let array = [1,2,3];
console.log(array);

for ( let arr of array ) {
   arr ++;
   console.log(arr)
   console.log(array)
}; 

Is this because arr will loop through the values but these are in local scope and don't affect the array lietral?
Turandeep Munday
Turandeep Munday
6,047 Points

I was expecting the array to be returned with all values in the array added by +1 but this wasn't the case.

2 Answers

Steven Parker
Steven Parker
231,269 Points

You're right, the loop variable "arr" is local in scope and only contains a copy of the current array element's value. So incrementing it will not affect the original array.

Modifying the array is easily done in a conventional loop:

for (let i = 0; i < array.length; i++) {
  array[i]++;
} 

Or using the "map" method:

array = array.map(arr => ++arr);  // note: post-increment won't work here
Turandeep Munday
Turandeep Munday
6,047 Points

Thanks - I assume it's not possible to change the array values in a let.. of loop?

Steven Parker
Steven Parker
231,269 Points

Not by modifying the loop variable. That's why a different kind of loop would make more sense.