functions with return
Hey, in a course i'm doing, there was a question asking that you create a secondary array with the original array items lengths. The solution i added is what's inside of the function. However, it wouldn't register as being correct unless i put
return
before strings.map
. I'm not really sure why it's important that's there. Is this because that's how it returns the array it creates back to you? And with the second return
returning string.length
, it that how it pulls the value it's looking for?
I'd appreciate any explanation. Thank you in advance.5 Replies
ok so is it that u thought adding that return within the map() will also return from the function?
in that case , let's refactor the code
maybe that'll help u understand why returning from inside the map() won't return fron rhe function
can u now understand how returning from the call back can't return from the getStringSizes?
return statements r scoped to their parent function. so when u say it return, it only returns from the parent function, not any of the grandparent function. which is why despite returning from within the map(), u still need to return from the getStringSizes()
when writing a function, the instructions inside are done in order; and yes, the return statement is what the function will send back when it completes, the return value. It's optional.
in JS you can write functions in multiple ways. Here you also use an arrow function, which automatically returns a value - unless it's an {object} in braces, in which case it needs the . So you can remove the braces and return from the map and have the same result with
or you can rewrite the whole works as a const and use arrow functions to avoid writing any returns and have something like this
The best way to learn the patterns is just use them and mess around, see what works and what breaks.
Keep in mind that its not avoiding returns its just making them implied
I realize you said avoid writing now 🤦♂️ brain but still good to clarify (which you I also missed you do LOL mbmbmb, going back to my coffee)
ah yeah i see why it doesn't return now, thank you. i'm used to adding
return xyz
as the last line of a function not adding it before anything, i think that's where i got confused. And thank you everyone else for the pointers!people usually forget this, but, you can return almost anywhere in a function
the use of arrow functions with the implied return will be very useful for you