Search code examples
javascriptloopsforeachnested-if

Javascript changing variable with if statement in forEach


*Use the existing test variable and write a forEach loop * that adds 100 to each number that is divisible by 3. * * Things to note: * - you must use an if statement to verify code is divisible by 3

I'm confused, why isn't my code working?

var test = [12, 929, 11, 3, 199, 1000, 7, 1, 24, 37, 4,
19, 300, 3775, 299, 36, 209, 148, 169, 299,
6, 109, 20, 58, 139, 59, 3, 1, 139
];

test.forEach(function(number) {
if (number % 3 === 0) {
    number += 100;

});


console.log(test[0]); **this is returning 12, NOT the desired 112**

Solution

  • You are not putting back the number in array.

    Primitives are not references. You need to use the index and put it back.

    test.forEach(function(number,index) {
    if (number % 3 === 0) {
        number += 100;
        test[index] = number;
    });