In a class I am taking they give an example of editing an Array's contents with a forEach() loop.
Classes Example:
var donuts = ["jelly donut", "chocolate donut", "glazed donut"];
donuts.forEach(function(donut) {
donut += " hole";
donut = donut.toUpperCase();
console.log(donut);
});
Prints:
JELLY DONUT HOLE
CHOCOLATE DONUT HOLE
GLAZED DONUT HOLE
The problem is when I try to solve a quiz problem using the same technique it doesn't change the arrays values. I believe this has to do with the if statement but they ask us to use it, so why would they not tell us there is an issue?
My Code:
/*
* Programming Quiz: Another Type of Loop (6-8)
*
* 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
* - you can use `console.log` to verify the `test` variable when you're finished looping
*/
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(element){
if (element % 3 === 0){
element += 100;
return element
}
});
console.log(test);
I have tried running return statements but no luck. I reached out to their "Live Help" but they were less than helpful. Can someone please tell me what I am not seeing here?
map?forEachis not appropriate in this scenario.donutis passed into the callback function by value, not by reference. Editingdonutonly edits the local copy of that string. Ifdonutwere an object, you could actually mutate it, because those are passed by reference. The classes’ example doesn’t change the original array as well.returninforEachdoes nothing... nowhere to return tomapdoesn't modify the array either, it creates a new one.