Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default export in ES6. Why don't you need a semicolon?

Tags:

ecmascript-6

I'm reading this from the exploringjs about ES6

17.1.2 Single default export

There can be a single default export. For example, a function:

//------ myFunc.js ------   
export default function () { ··· } // no semicolon!

//------ main1.js ------  
import myFunc from 'myFunc';
myFunc();

Or a class:

//------ MyClass.js ------  
export default class { ··· } // no semicolon!

//------ main2.js ------  
import MyClass from 'MyClass';
let inst = new MyClass();

Note that there is no semicolon at the end if you default-export a function or a class (which are anonymous declarations).

Why do you not use a semi-colon at the end of the export default declaration? I thought you end all statements with semi-colons?

like image 405
Jwan622 Avatar asked Nov 02 '15 16:11

Jwan622


2 Answers

Why don't you need a semicolon?

Because the grammar doesn't define a semicolon there:

export default HoistableDeclaration
export default ClassDeclaration
export default [lookahead ∉ {function, class}] AssignmentExpression ;

(unless you have an expression)

I thought you end all statements with semi-colons?

That's not true at all. Have you ever put a semicolon after a block? If someone writes

if (...) {

};

then it is by mistake.

It may seem that all statements are terminated by semicolons, because at the end / bottom of most statements, you end up having an ExpressionStatement or empty statement, which both are terminated by semicolons.

Besides that, an ExportDeclaration is not a statement.

like image 136
Felix Kling Avatar answered Sep 22 '22 18:09

Felix Kling


I thought you end all statements with semi-colons?

Yes, but declarations are no statements. This is not specific for exports, you don't put semicolons after normal function declarations either.

Btw, in statements you don't actually need semicolons, as JavaScript has automatic semicolon insertion - it only is good practise.

like image 20
Bergi Avatar answered Sep 22 '22 18:09

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!