-2

I'd like to declare a function like this:

function calculateArea(length, width) {return length * width;}

using arrow function expression syntax, like this:

function calculateArea(length, width) => length * width;

But doing so causes an error.

1) Can someone explain why JavaScript arrow function syntax can't be used in a function declaration?

2) Are there any nearby alternatives that approximate using an arrow function in a function declaration?

Honestly, it's not a big loss if it can't be done, but I'd like to understand whether there's some deeper reason why this doesn't work, or if this is simply a limitation of the language at present.

  • 1
    but whats the point? why not use arrow function? – Dmitry Reutov Jun 10 '20 at 20:34
  • 1
    It does work, you're mixing `function` with fat arrow, i.e. `const calculateArea = (length, width) => length * width;` – Phix Jun 10 '20 at 20:34
  • 1
    What is your goal in trying to mix both types of function declaration? What do you hope to achieve? – Pointy Jun 10 '20 at 20:38
  • @Pointy In places, the MDN [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) on arrow function expressions seems to imply that ```=> expression``` is a shorthand for ```{return expression}``` . The fact that the one isn't uniformly substitutable for the other shows this isn't strictly correct. Maybe there's no deeper reason for this than "that's not the syntax". But the substitution failure suggests I'm missing something about arrow function expressions, and I'd like to understand whether that's the case, and if so what I'm missing. – Jacob Archambault Jun 10 '20 at 20:56

2 Answers2

2

Can someone explain why JavaScript arrow function syntax can't be used in a function declaration?

Because it isn't function declaration syntax.

Are there any nearby alternatives that approximate using an arrow function in a function declaration?

No.


You can create functions with:

  • Function declarations
  • Function expressions
  • Arrow functions
  • Shorthand method declarations
  • The Function constructor (don't use this)

The syntax for them is not mix and match.


If you want an arrow function, use an arrow function.

const calculateArea = (length, width) => length * width;

… and position it in your code so that it does not require hoisting.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

There is this way:

const calculateArea = (length, width) => length * width;