0

Consider the following code:

`abc`.split(`b`)
`abc`.split(`b`)

This fails with TypeError: "abc".split(...) is not a function

Try it here.

To make it work, we need to insert a semicolon between those two statements. Also the code works fine if we use a regular string on the second line:

`abc`.split(`b`)
"abc".split(`b`)

What is the reason for this behaviour?

I guess it has something to do with the automatic semicolon insertion doing some whacky stuff, but I can't figure out what this would be.
Also the fact that there seems to be a difference between regular and template strings kinda confuses me. Shouldn't those be equivalent?

Denker
  • 115
  • 2
  • 6
  • 1
    Automatic insertion of semicolons doesn't mean you can always leave them out, in some cases they are indeed needed to avoid issues, this seems to be one of those times where you end up with valid syntax where the semicolon isn't inserted. – adeneo Feb 03 '17 at 23:49

1 Answers1

6

Template literals can be tagged with a function, string literals cannot. Notice that

tag`a ${x} b`;

is basically equivalent to

tag("a ", x, " b");

Since your expression `abc`.split(`b`) `abc`.split(`b`) is grammatically valid, there is no automatic semicolon insertion happening here. Don't omit the semicolons where they are necessary. It's not that ASI is doing whacky stuff, it's just doing nothing while you expect it to.

If you want to omit semicolons and let them be automatically inserted where ever possible needed, you will need to put one at the begin of every line that starts with (, [, /, +, - or `.

Bergi
  • 513,640
  • 108
  • 821
  • 1,164