Returning Values in Arrow Functions
It's common knowledge that if a single statement follows the arrow function declaration, it returns the result of that statement:
a=>{return a+3}
a=>a+3
-7 bytes
So when possible, combine multiple statements into one. This is most easily done by surrounding the statements with parenthesis'parentheses and separating them with commas:
a=>{r=0;a.map(n=>r+=n);return r}
a=>(r=0,a.map(n=>r+=n),r)
-8 bytes
But if there are only two statements, it is usually possible (and shorter) to combine them with &&
or ||
:
a=>{r=0;a.map(n=>r+=n);return r}
// - Use && because map always returns an array (true)
// - declaration of r moved into unused map argument to make it only 2 statements
a=>a.map(n=>r+=n,r=0)&&r
-9 bytes
Finally if you are using map (or similar) and need to return a number and you can guarantee the map will never return a 1-length array with a number, you can return the number with |
:
a=>{a=b=0;a.map(n=>(a+=n,b-=n));return a/b}
// - {} in map ensures it returns an array of undefined, so the | will make the returned
// array cast from [ undefined, undefined, undefined ] to ",," to NaN to 0 and 0|n = n,
// if the map returned [ 4 ] it would cast from [ 4 ] to "4" to 4 and make it 4|n
a=>a.map(n=>{a+=n,b-=n},a=b=0)|a/b