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?

2
  • 3
    You're using an assignment operator "=" instead of "==" or "===". Commented Dec 9, 2017 at 13:52
  • looks like an assignment issue Commented Dec 9, 2017 at 13:54

4 Answers 4

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]
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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
    

1 Comment

Good question, all that replied got an instant downvote ;)
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);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.