1

Here is my code JS :

var items = [255, 255, 255, 255];
items.forEach(function(item) {
    if (item = 255) {
        item = 0;
    };
});
console.log(items)

In console.log I get [255, 255, 255, 255], why it doesn't change to [0, 0, 0, 0]? What am I doing wrong?

Gerardo Furtado
  • 100,839
  • 9
  • 121
  • 171
bafix2203
  • 541
  • 7
  • 25

4 Answers4

1

You want to use .map.

.forEach doesn't return anything, it is used to run a function with each item. .map returns a value for each iteration it runs.

var items = [255, 255, 255, 255]
items = items.map(item => item === 255 ? 0 : item)

console.log(items) // [0, 0, 0, 0]
Dan Gamble
  • 3,965
  • 1
  • 24
  • 44
1

Well, you are just changing the value type argument, nothing will happen with the items in the array. You can just change it to use map instead and create a new array

items = items.map( item => item === 255 ? 0 : item );

As remarked in the comments, in the original code, you also used an assignment operator instead of a compare operator

When you do:

if (item = 255) 

You will assign item with 255 (which will be truthy, and then go into the if statement where you are assigning it with 0)

Icepickle
  • 12,689
  • 3
  • 34
  • 48
1

Your code contains two bugs.

  1. = is assignment, not comparison. Your function is equivalent to:

    function (item) {
        item = 255;
        item = 0;
    }
    
  2. item is a function parameter, i.e. a local variable in the anonymous function. Assigning to item has no effect on the items array:

    var x = 255;
    (function (y) { y = 0; })(x);
    console.log(x);
    // 255
    
melpomene
  • 84,125
  • 8
  • 85
  • 148
0

You could take the reference to the array for changing the value inside of the callback for Array#forEach.

BTW, after a block statement, there is no need for a semicolon.

var items = [255, 255, 255, 255];

items.forEach(function(item, index, array) {
//                                  ^^^^^
    if (item = 255) {
        array[index] = 0;
    }
//   ^ no semicolon needed
});

console.log(items);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392