1

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
1
  • forEach and map do different things, they aren't interchangeable Commented Aug 2, 2019 at 23:45

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}
answered Aug 3, 2019 at 0:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.