Why doesnt forEach work here?

Why doesnt forEach work here?


it’s really confusing me.

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


thank you campers


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

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

apologies. this still doesn’t work though


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


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.


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).


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


thank you very much for the help


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.