4 ms·
I've been pondering a few style questions recently: 1. When to use 'function' vs '=>'? Leaving aside hoisting and handling of 'this', 'function' and '=>' are
by peferron 12y ago
I've been pondering a few style questions recently:
1. When to use 'function' vs '=>'?
Leaving aside hoisting and handling of 'this', 'function' and '=>' are usually interchangeable:
function foo(x) {
// do something
}
let foo = x => {
// do something
}
I prefer to keep using 'function' because it's immediately obvious to the reader that we are creating a function. With '=>', the reader doesn't know if foo is a function or not until reaching '=>', which is located after the argument list. There's also almost no terseness gain. A potential win for '=>' though would be the ability to declare the function as 'const'.
With closures, '=>' wins because the reader already expects a function, and the terseness gain is significant:
somearray.map(function(x) {
// do something
});
somearray.map(x => {
// do something
});
2. When to use {} around the function body?
somearray.forEach(x => /* a single statement */);
somearray.forEach(x => {/* a single statement */});
{} around the function body are optional if there's only a single statement. However, for clarity, I still use {} when I want to make it clear that we are not using the return value. I think that might be overkill though: the reader should aready expect that 'map', 'filter' and friends will use the return value, while 'forEach' will not.
3. 'let' or 'const'?
This one is already mentioned in a sibling comment, so let's keep the discussion there.
I realize that these are tiny style decisions that will probably incite endless bikeshedding, but I'm still interested in hearing opinions from fellow HNers. :)
- jarcane 12y agoHaskell possesses similar syntax, save that one must prefix an anonymous function with \, like so: \x -> x * 42 It's possible as well to use it bare like that, but only in very particular places, so it's generally much clearer to use it wrapped in parens: (\x -> x * 42) Perhaps some similar convention would make it clearer where a lambda is being used in .js?
- lewisl9029 12y agoI wish named arrow functions could make it into the spec, but until then, I'll personally stick with the full, named function declaration for all of my functions because it makes stack traces much more readable, which far outvalues the saved keystrokes that arrow functions provide when building non-trivial applications.