Andrey Bushman
Andrey Bushman

Reputation: 12476

Semicolon before (()=>true)()

It works fine:

const foo = 1; // any number, string, bolean or object
(() => console.log('stuff'))()

But it doesn't work without semicolon:

const foo = 1 // TypeError: 1 is not a function
(() => console.log('stuff'))()

Hm...
Should not the call of an anonymous function be treated as a separate instruction in the case when the first bracket can not be interpreted as a correct continuation of the previous instruction?

Upvotes: 0

Views: 63

Answers (4)

nitobuendia
nitobuendia

Reputation: 1248

You should alway use semicolons. If you do not add them, Javascript will guess where to insert them and will lead to errors.

In your case, it is interpreting that you are calling a function.

A good article on the topic on how semicolons are automatically inserted:

The norm: The parser treats every new token as part of the current statement, unless there is a semicolon that terminates it. The following examples show code where you might think a semicolon should be inserted, but isn’t. This illustrates the risks of omitting semicolons.

No ASI:

a = b + c
(d + e).print()

This does not trigger ASI, because the opening parenthesis could follow c in a function call. The above is thus interpreted as:

a = b + c(d + e).print();

Upvotes: 1

melpomene
melpomene

Reputation: 85757

Yes, but it's only about syntactically correct continuations.

1(() => console.log('stuff'))()

is a syntactically correct expression and parses as "call 1 with an argument of () => console.log('stuff'), then call the result of that without arguments". This throws an exception at runtime (1 is not function, so it can't be called), but it's still a valid expression.

Upvotes: 1

Jiachen Guo
Jiachen Guo

Reputation: 281

in javascript, it doesn't matter how many spaces you have, it will just be treated as one space only.

in your second code snippet, it just actually equals:

const foo = 1 (() => console.log('stuff'))()

which means you invoke a function called '1' and pass '()=>console.log('stuff')' as an argument. but apparently 1 is not a function, so it throw an error, hope make sense to you

Upvotes: 0

Bergi
Bergi

Reputation: 664195

…when the first bracket can not be interpreted as a correct continuation of the previous instruction?

But it can - as you can see, the code parses just fine, and executes. That it will throw a runtime exception when no semicolon isn't inserted doesn't matter to the ASI, it cannot know while parsing.

Upvotes: 0

Related Questions