Arrow functions syntax in javascript
Preface
I was surprised by how incosistent and weird es6 arrow functions syntax is. I have counted twelve different ways of creating arrow function. Check this out:
// Parentheses are required if there are no parameters
() => 'foo' // 'foo'
() => { return 'foo' } // 'foo'
() => {} // undefined
() => ({ foo: 'bar' }) // { foo: 'bar' }
// Parentheses are optional if there is only one parameter
x => 'foo' // 'foo'
x => { return 'foo' } // 'foo'
x => {} // undefined
x => ({ foo: 'bar' }) // { foo: 'bar' }
// Parentheses are required if there are more that one parameter
(x, y) => 'foo' // 'foo'
(x, y) => { return 'foo' } // 'foo'
(x, y) => {} // undefined
(x, y) => ({ foo: 'bar' }) // { foo: 'bar' }
Summary
On the left side:
- Parentheses are required if there are no parameters
- Parentheses are optional if there is only one parameter
- Parentheses are required if there are more that one parameter
On the right side:
- Braces and
return
are optional if there’s only one expression - Braces and
return
are required if there’s more than one expression - Braces are required if function does nothing (or returns undefined)
- Braces and
return
are optional if there’s one expression which returns object. But object should be put into Parentheses.
There are 7 rules and 12 combinations and you will probably have to remember them all to read and write arrow functions. This is wrong.
Why can’t we have one way of creating a function? Like we have with regular functions? Why not take the regular function syntax and replace function
with =>
?
function(...){...}
// should have just become this
(...) => { ... }
Always use the “full” syntax
Only the full version of arrow function syntax can be used in any situation. So I think we should configure linter to
allow only (...) => {...}
syntax in our applications. For the sake of consistency!