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')
CodePudding user response:
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(', ')
);
CodePudding user response:
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);