Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need a semicolon after a named export function declaration

First, this is NOT a question about ASI. I'm not asking whether or not automatic semicolon insertion applies here (well, I kind of am, but that opening statement is an attempt at avoiding arguments between whether I should or shouldn't use a semicolon because asi will take care of it for me...)

I know not to put a semicolon after a function declaration...

function foo() { 
  // do stuff
} // no semicolon

But do I need a semicolon after exporting a function declaration?

export function foo() {
  // do stuff
} // semicolon or not to semicolon?

In either case, I would also love to know why.

like image 745
sfletche Avatar asked Jan 05 '23 23:01

sfletche


2 Answers

No, you do not need a semi-colon, though adding one will do no harm.

If we look at the ES6 spec, you will see that this signature is considered a declaration and, like normal function declarations, does not need a semicolon after it:

export Declaration

The statements that need to be followed by a semi-colon (whether explicit or implicit) are noted as such in that document. For example:

export * FromClause ;

There the ; is mandatory. In the declaration, it is not. Of course, inserting the semicolon will not do any harm; the JS interpreter will treat it as an empty statement.

like image 173
lonesomeday Avatar answered Jan 08 '23 06:01

lonesomeday


No, you don't need a semicolon here. See this example from MDN:

export default function() {} // or 'export default class {}'
// there is no semi-colon here

See also the ECMAScript specification:

Syntax

ExportDeclaration :
  export * FromClause ;
  export ExportClause[~Local] FromClause ;
  export ExportClause[+Local] ;
  export VariableStatement[~Yield, ~Await]
  export Declaration[~Yield, ~Await]
  export defaultHoistableDeclaration[~Yield, ~Await, +Default]
  export defaultClassDeclaration[~Yield, ~Await, +Default]
  export default[lookahead ∉ { function, async [no LineTerminator here] function, class }]AssignmentExpression[+In, ~Yield, ~Await] ;

As you see, there's no semicolon after Declaration.

like image 23
Michał Perłakowski Avatar answered Jan 08 '23 08:01

Michał Perłakowski