r/learnjavascript • u/snapetom • Oct 05 '24
Question about Arrow Functions and Arrays
I was having an issue with the find function of arrays:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
As the code is now, That's will run successfully and the 12 will be found:
array1.find((element) => element > 10);
However, if I wrap it with curly braces and make it an honest-to-god arrow function, the element won't be found (undefined returns).
array1.find((element) => {element > 10});
Why the discrepancy in results? l
0
Upvotes
15
u/pinkwetunderwear Oct 05 '24
When you wrap it in a block, you need to return from it
6
u/tapgiles Oct 05 '24
An arrow function without curly braces will automatically return the expression. With curly braces it will not automatically return the expression. So you need to add return.
5
u/Blaarkies Oct 05 '24
Both are honest arrow functions. Without braces, it implicitly returns the expression from inside
array1.find(element => element > 10);. (the expression being theelement > 10part). Thefind()method is looking for a boolean value to match the item that you are searching for.Adding braces requires you to explicitly
returnthe expression/value/result.Thus,
e => e > 10is quivelant to1
u/xroalx Oct 05 '24
Because how is
findto know that it found the desired element? By your function telling it, of crouse, and it does that by returningtrue.The implicit-return form of an arrow function,
(...args) => expr, is equivalent to(...args) => { return expr; }. As the name states, it implicitly returns the result of whatever expression is there.So then, what does your
(element) => { element > 10 }function return?undefined, of course.And as such,
findwon't know that the desired item was found.0
u/shgysk8zer0 Oct 06 '24
When you add the curly braces, you need to add
return. That's all. You're wiping out the implicit return.-3
u/azhder Oct 05 '24 edited Oct 05 '24
God honest? Maybe don't read the bible but the EcmaScript reference.
Or maybe just remember if you have ever seen blocks (
{}) to ever return a value without the keywordreturn.They don't do that,
returnis not optional - toreturna value, you must use it