Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the es6 fat arrow equivalent to a es5 function declaration

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 ??
like image 408
thedanotto Avatar asked May 31 '19 19:05

thedanotto


2 Answers

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() {}
}
like image 117
Omar Avatar answered Sep 19 '22 19:09

Omar


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() {
        // ...
    }
}
like image 29
ChrisD Avatar answered Sep 16 '22 19:09

ChrisD