1

I am working with forEach statements right now and I have a block of code here that successfully executes what I am working on but I don't understand one particular statement. I did not write this code.

let test = [10, 12, 14, 15, 16, 18];

test.forEach(function(num, index, array) {
  if (num % 3 === 0) {
    array[index] = num += 100; // <- This is the line of code that I am confounded by
  }
});
console.log(test);

I simply don't understand the logic behind it.

Sorry if the question is poorly phrased this is my first coding related question I've ever posted, thanks for the help.

2
  • 1
    If the number is a multiple of 3, increment the number at that index by 100. Like 12 is a multiple of 3. This will result in 12 + 100 = 120. Commented Oct 15, 2019 at 13:00
  • num += 100 is shorthand for num = num + 100. Commented Oct 15, 2019 at 13:15

1 Answer 1

1

Here is the solution you are looking for:

I don't think array[index] = num += 100; is weird.

First of all num += 100 is adding 100 to current number and finally assigning it to array[index]

Below is the simplified version of your code

let test = [10, 12, 14, 15, 16, 18];

test.forEach(function(num, index, array) {
  if (num % 3 === 0) {
    num = num + 100;    // Adding 100 to old value (identical to num += 100)
    array[index] = num; // I do't think this is a weird code now
  }
});
console.log(test);

Hope this will help Thanks.....

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the comment Shrirang, the main part that I am confused by is the array[index] = num, I believe that my understanding of the forEach statement is lacking. I see on MDN documentation that the index / array part of the function is optional, however I don't really get why this code is written with array[index] = num if indeed those two are optional. Thanks again
@ndanvers I understood your doubt. As per my understanding if you want to perform any operations on array elements then you can use index and array, but if you are not doing any modification on array then these parameters are optional. On MDN documentation there are many examples please look into it you will get the fair idea that what I am trying to say.
@ndanvers I am mentioning some scenarios where index and array parameters are optional. 1) If you want to print array elements 2) If you want to copy array elements into another array
Thank you very much for your comments Shrirang you’ve helped a lot :)
@ndanvers If you are satisfied you can mark this answer.
|

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.