Reputation: 61
I want to know why forEach would not work on this array but map does work.
I tried to use .map and it works but shouldn't forEach work as well
function letters() {
let string = "abcd";
let newString = string.split("").forEach(i => {
return String.fromCharCode(i.charCodeAt(0) + 1);
});
newString = newString.join("");
}
I get undefined when I use forEach
Upvotes: 1
Views: 32
Reputation: 88
If you want to use forEach
:
function letters() {
let string = "abcd";
let newString = '';
string.split("").forEach(i => {
newString += String.fromCharCode(i.charCodeAt(0) + 1);
});
return newString;
}
Upvotes: 0
Reputation: 780798
shouldn't forEach work as well
No, it shouldn't. The documentation says:
Return value
undefined
This is the difference between map
and forEach
. They both call the function for each element of the array. map
returns a new array containing the results, forEach
ignores the results and doesn't return anything.
Upvotes: 1