I am totally new to coding so my question is probably very basic. I want to loop over the following array and every time the number is divisible by 3 I want to add 100. If not, just print the number. I want to do that with the forEach() method. This is my code but when I want to print it it says "undefined" What am I doing wrong?
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(num){
if(num %3 === 0){
return num+=100;
}else{
return num;
}
console.log(num) ;
})
.forEach()method always returnsundefinedforEachworks just fine, no need to usemap. If you want to transform the numbers and use the transformed numbers somewhere else,mapis more appropriate. You may also want to search for "immutability" to understand whymapmay be a better solution.