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
asked Aug 2, 2019 at 23:43
tjsims8819
611 gold badge1 silver badge6 bronze badges
2 Answers 2
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.
answered Aug 2, 2019 at 23:47
Barmar
789k57 gold badges555 silver badges669 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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;
}
Comments
lang-js
forEachandmapdo different things, they aren't interchangeable