Difference between ()=> and _=> and (_)=> in JS ES6
The general form of a fat-arrow function is
(parameter-list) => function-body
If you don't have any parameters, you use a pair of empty parentheses:
() => {}
If you have a single parameter it's:
(x) => {}
Since _
is a valid identifier in JavaScript, you can do:
(_) => {}
Now, a special rule applies: If you have only one parameter, you can skip the parentheses, so you get:
_ => {}
Please note that this is only valid if you have a single parameter, i.e. for two you always have to specify the parentheses:
(x, y) => {}
Now, on the right side, if your entire function only consists of a single statement with a return
, such as
x => { return x; }
you can omit the curly braces and the return
:
x => x
At least, this is true if on the right side you don't try to return an object, which would look like this (this code won't work!):
x => { value: x }
The reason why this does not work is that JavaScript can not distinguish this from a function body, which also uses curly braces, so now you have to wrap it in parentheses:
x => ({ value: x })
I think that's pretty much everything you need to know about the syntax of fat arrow functions.
You should not use something just because it looks cool.
_
is often used to tell a linter (or reader) that you do not use an certain argument on purpose.
So if you have a callback with two arguments and you only use the second one you would write (_, arg) => console.log(arg)
because if you would write (foo, arg) => console.log(arg)
then the linter would complain about foo
not being used.
And some APIs might have different behavior depending on the number of arguments the callback has (the middlewares of expressjs are an example for that), so if the API checks the length
property of the callback then you might need to use a placeholder like _
.
var cb1 = _ => {};
var cb2 = () => {};
console.log(cb1.length)
console.log(cb2.length)