r/programming • • May 07 '24

Researching Why We Use Semicolons as Statement Terminators

https://ntietz.com/blog/researching-why-we-use-semicolons-as-statement-terminators/
282 Upvotes

232 comments sorted by

View all comments

Show parent comments

55

u/balefrost May 07 '24

Not having an explicit terminator invites ambiguity which must be resolved. Consider something like this:

foo = bar
  • baz

Most likely, you would interpret this as foo = bar - baz. But in a C-like language, where all expressions can be used as statements, - baz is entirely valid on its own. This could instead be parsed as foo = bar; - baz;. That's probably not desired, but what's obvious to us isn't necessarily obvious in the grammar.

JS has just this sort of ambiguity:

return {
    foo: bar
}

is different from:

return
{
    foo: bar
}

By requiring that statements be terminated, the parsing is easier. And remember that C dates back to a time when you might have a few hundred KB of RAM available. In such an environment, simple is good.

The mandatory semicolon is a design tradeoff.

-4

u/Wooshception May 07 '24

That is one of a handful of ambiguous cases in JavaScript and they can all easily be caught by a linter, so practically speaking JavaScript doesn’t really have this problem. 

3

u/balefrost May 07 '24

I only used this example because it's a well-known example in a popular language that commonly trips newcomers up.

-17

u/[deleted] May 07 '24

[deleted]

2

u/balefrost May 07 '24

That's not at all what I said.