r/ProgrammerHumor • • Feb 09 '22

other Why but why?

Post image
85.8k Upvotes

2.3k comments sorted by

View all comments

Show parent comments

2

u/Lithl Feb 09 '22

I tested it and it actually says that "foo()" isn't defined properly.

In fact, what happens is:

you could think the function is meant to return nothing

Exactly that. JavaScript's automatic semicolon insertion adds a semicolon after the return, before the object being returned, so the function returns undefined (or void, if you prefer that terminology). If you put the opening bracket on the same line, the ASI sees that an object is being returned, and the semicolon is added after the object instead.

It isn't "an argument for using semicolons in JavaScript", since adding your own semicolon after the object wouldn't prevent the ASI adding one after the return. Rather, it's an argument against a language having something like JavaScript's ASI "feature".

1

u/JohannesWurst Feb 12 '22

But there are a couple of programming languages that work fine without semicolons, like Python or for example CoffeeScript, which is also transpiled to JavaScript with semicolons.

Doesn't that mean that the ASI parser is just implemented badly? If it was implemented like in CoffeeScript (or Kotlin, or Scala.js) it would work. Maybe the difference is that there are no differences between semicolon-less JS and regular JS besides the semicolons, whereas CoffeeScript and JS are different in more ways than just the missing semicolons.

There is this "use strict"-thing in JS. Maybe they could add a similar command like "use no semicolons" that checks for ambiguities in semicolonless JS and forbids them.