0

I’m trying some tester code I turn a string into UpperCase Then split it to make it into an array and then loop through it using ES6 forEach loop However when I try to concatenate ‘hello’ to the subject of the loop It returns undefined

const string = 'abcd'
console.log(string.toUpperCase().split('').forEach(element => element += 'hello'))

And when I add join(‘’) to it it returns this

undefined is not an object (evaluating string.toLowerCase().split('').forEach(element => element +=('hello')).join')
1
  • 2
    forEach does not return anything accept its undefined default value. Please read some documentation ... forEach, map, reduce Commented Sep 19, 2021 at 7:58

2 Answers 2

2

You need to use map function to make any changes to array elements

const string = 'abcd';

console.log(
  string
    .toUpperCase()
    .split('')
    .map(char =>
      char += ' hello'
    ).join(', ')
);

Sign up to request clarification or add additional context in comments.

Comments

0

map is the proper way to do it, but if you need to use forEach, use it like that:

const string = 'abcd'
var newstr = '';
string.toUpperCase().split('').forEach(element => newstr += element + 'hello');
console.log(newstr);

Comments

Your Answer

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.