3
var prev = a = new Date() => a; // Error

var prev = (a = new Date()) => a; // Good

In the arrow functions, when it is only a parameter, I can omit the parentheses, however when I do this, I must add them.

Is it an error in the architecture of language, or is it the structure of the language itself?

Etheryte
  • 24,589
  • 11
  • 71
  • 116

3 Answers3

4

In first case you are trying to declare 2 variables: prev and a. And the value you are assigning is incorrect. The result is the same as if you tried to execute new Date() => a directly in the console:

Uncaught SyntaxError: Unexpected token new

In second case you are declaring only one variable prev. And the value is a function with one argument a set by default to new Date().

See also In JavaScript, is chained assignment okay?

dhilt
  • 18,707
  • 8
  • 70
  • 85
3

Parenthesis are required around your arrow function when using a default value.

// Correct approach for default values
var prev = (a = new Date()) => a;

// Incorrect approach
var prev = a = new Date() => a; // Nope. Where does the arrow function start?
var prev = a = (new Date()) => a; // Invalid parameter name right?

Why?

Because in var prev = a = new Date() => a; the compiler thinks you are asking:

  • Make prev equal the value a which equals the value of an arrow function with new Date() as the parameter name? Error!

It's not explicit enough so the compiler doesn't like it. If you have defaults wrap them in parentheses.

Read more on MDN Default Params

Bradley Flood
  • 10,233
  • 3
  • 46
  • 43
0

If you look at ecmascript spec for arrow function hasinitializer, you can see the definition for an arrow function that has an iniitializer:

ArrowParameters : CoverParenthesizedExpressionAndArrowParameterList

and the definition of CoverParenthesizedExpressionAndArrowParameterList is:

CoverParenthesizedExpressionAndArrowParameterList[Yield] : ( Expression[In, ?Yield] ) ( ) ( ... BindingIdentifier[?Yield] ) ( Expression[In, ?Yield] , ... BindingIdentifier[?Yield] )

You can see that when you have a default initializer, arrow params must be in (), so it is a structure of the language itself

JohanP
  • 5,252
  • 2
  • 24
  • 34