Question on Functions and .map

This is the exercise I’m currently on: Practice JavaScript Syntax: Arrays, Loops, Objects, Iterators | Codecademy

Here’s a screenshot of the problem I’m encountering, I’ve put the question in the screenshot as well in the comments.

Hello! The reason the return must be on the outside of .map is because .map is a function which automatically returns the values it gets from the expression you give it. In your case, map automatically returns the result of squaring each value of num in the array. However, the squareNums function also needs to return something, otherwise there won’t be any data to give back to the rest of the program.

1 Like

Great you’re experimenting things in the lessons. I tried to do the same thing after completing all the instructions.
Some iterator function return the value after using the callback function (function passed in () ) on every element.

.map() takes in a function which needs to have a parameter for every element. In that function you have to do the calculation you need and return the value. What happens is .map() takes the returned value for every element being called with the function, arranges them in an array and then return the array. So if you don’t return any value a default value undefined gets returned.

In the third example you wrote:

const squareNumsNotWorking = (arr) => {
    return arr.map(num => {num * num});
}

In the return statement you wrapped num * num in {}. This doesn’t returns the value. To return you should either add a return in front of num * num or remove {} from num * num.

1 Like