With ES5 I can declare either a function declaration or expression, depending on what I need.
function es5FunctionDeclaration() {
return 'I am an es5 function declaration';
}
var es5FunctionExpression = function() {
return 'I am an es5 function expression';
}
With the ES6 fat arrow, it is common to create a function expression like this...
const es6FunctionExpression = () => {
return 'I am an es6 function expression';
}
But I haven't find a way to do a function declaration with a fat arrow, perhaps it is not possible.
// es6FunctionDeclarationWithFatArrow ??
To declare functions in ES6 you can do it via:
const functionName = () => {};
Or you can do it via the function
keyword:
function functionName() {}
And, if you're creating ES6 classes you don't create functions but methods:
class MyClass {
constructor() {}
method1() {}
method2() {}
}
The definition of an arrow function is here: http://www.ecma-international.org/ecma-262/6.0/#sec-arrow-function-definitions
ArrowFunction[In, Yield] :
ArrowParameters[?Yield] [no LineTerminator here] => ConciseBody[?In]
ArrowParameters[Yield] :
BindingIdentifier[?Yield] CoverParenthesizedExpressionAndArrowParameterList[?Yield]
ConciseBody[In] :
[lookahead ≠ { ] AssignmentExpression[?In] { FunctionBody }
What this means in English, is that an arrow function can only be declared like so args => {}
and that's it. As you say, you can bind it to a variable with, for example, const func = args => {}
or by passing it as an argument to another function, but there's no way. Indeed, passing an arrow function as an argument was one of the major reasons it was created (because of binding this
). See lexical this (and the appendix)
As @MaheerAli has mentioned, arrow functions neatly avoids function hoisting which may be surprising behaviour.
ES6 does have some ways to declare functions in a shorter manner, such as within objects:
const obj = {
func() {
// ...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With