Why doesnt forEach work here?

Why doesnt forEach work here?
0

#1

it’s really confusing me.

function arrayItemLengths() {
let sortedArray =  ["anana", "ana", "ana", "nan"]
return sortedArray.forEach(
function(element){`${element}: length ${element.length}`})
}

console.log(arrayItemLengths())

thank you campers


#2

You’re not returning anything in the callback, so nothing happens.


#3
return sortedArray.forEach(
function(element){return `${element}: length ${element.length}`})

apologies. this still doesn’t work though


#4

What do you think this should do? I think you’re expecting it to do something it won’t do


#5

hmmm
to take each element in the array, write out its name and length in a new array, and then return that array when the function is called.


#6

You need a new array to push the string you created (but did not do anything with) into. You want to return the new array and not the sortedArray (which your current attempts to do but fails).


#7

Check out the difference between Array.forEach and Array.map. :wink:


#8

thank you very much for the help


#9

forEach is designed for side effects - like adding things to the DOM, or logging to console. If you get rid of the return inside the callback, and wrap the string in a console.log, it’ll work how you expect it to but I think map is the one that will actually do what you want it to do - in that, anything you put into it will spit out a list of all of those strings converted to the string you’ve defined.