62

Python and JavaScript both allow developers to use or to omit semicolons. However, I've often seen it suggested (in books and blogs) that I should not use semicolons in Python, while I should always use them in JavaScript.

Is there a technical difference between how the languages use semicolons or is this just a cultural difference?

Jeremy
  • 1
  • 85
  • 340
  • 366
wong2
  • 34,358
  • 48
  • 134
  • 179
  • 2
    How is this "not constructive"? – NullUserException Aug 28 '11 at 07:21
  • 1
    @NullUser: this isn't Wikipedia, but can you point to a definitive reference, one that has a basis in something other than convention? – outis Aug 28 '11 at 07:34
  • @outis What do you mean? – NullUserException Aug 28 '11 at 07:35
  • 3
    I'd suggest re-titling this question something like "What are the difference between the ways that Python and JavaScript handle newlines and semicolons?". As phrased, it could be interpreted as more of a question about culture than technical differences. This is probably why people are voting to close. – Jeremy Aug 28 '11 at 08:09
  • 3
    This is an example that separating `programmers.stackexchange` of `stackoverflow` is a delicate situation. – BrainStorm Aug 28 '11 at 13:34
  • 3
    @wong2: I've edited the question to make it focus more on the objective technical side than the subjective cultural side, in hopes of having it reopened. Please feel free to undo this edit if you don't agree with it. – Jeremy Aug 30 '11 at 14:56

7 Answers7

72

Semicolons in Python are totally optional (unless you want to have multiple statements in a single line, of course). I personally think Python code with semicolons at the end of every statement looks very ugly.

Now in Javascript, if you don't write a semicolon, one is automatically inserted1 at the end of line. And this can cause problems. Consider:

function add(a, b) {
  return
    a + b
}

You'd think this returns a + b, but Javascript just outsmarted you and sees this as:

function add() {
  return;
    a + b;
}

Returning undefined instead.

1 See page 27, item 7.9 - Automatic Semicolon Insertion on ECMAScript Language Specification for more details and caveats.

NullUserException
  • 83,810
  • 28
  • 209
  • 234
  • So the point is that JavaScript will automatically insert semicolon at the end of line while Python wouldn't? – wong2 Aug 28 '11 at 07:19
  • 2
    In Python your statements have to be properly terminated or it will give you a syntax error. Besides, how would you accomplish something like this without triggering an unexpected indent error? – NullUserException Aug 28 '11 at 07:27
  • 1
    In fact, the only situation in which i find myself using semicolons in Python is when using `timeit` from the command-line. Semicolons allow you to have multiple statements in one line. – Björn Pollex Aug 28 '11 at 07:28
  • 4
    FYI: This answer does not continue to explain why `return \n a+b;` would not cause the outsmarting to `return; \n a+b;` as well, but Jeremy Bank's answer below explains that: **JavaScript will only treat a newline as a semicolon if it's a syntax error not to**. – Konerak Aug 28 '11 at 11:23
  • 1
    @Konerak Jeremy Banks lied to you. A semicolon is automatically inserted for any return statement followed by a newline. This is a pretty common source of bugs, especially among people who like placing the opening brace of their object literals on a new line. – sethobrien Sep 03 '11 at 07:46
  • 1
    @sethobrien: I was trying to simplify things, but seem to have done a pretty bad job. I'll edit my post to explain the details, rather than try to gloss over them. – Jeremy Sep 03 '11 at 09:25
  • Yes, it’s true, JavaScript adds a semicolon in that code, where Python wouldn’t. But your answer doesn’t explain why most people write out semicolons in JavaScript. Writing semicolons in your code sample [doesn’t fix it](http://mislav.uniqpath.com/2010/05/semicolons/) – only deleting the newline fixes it. [Jeremy’s answer](http://stackoverflow.com/a/7219779/578288) better explains why most JavaScripters write semicolons. – Rory O'Kane Jun 22 '12 at 16:43
  • Just to clarify: there are two ways to continue a statement on the following line in Python: explicit continuation (backslash) or implicit continuation (open paren, bracket...). The implicit one is preferred. See here on SO: http://stackoverflow.com/questions/53162/how-can-i-do-a-line-break-line-continuation-in-python and in the Python documentation: https://docs.python.org/3/reference/lexical_analysis.html#line-structure –  Aug 08 '16 at 12:42
69

This had me confused for the longest time. I thought it was just a cultural difference, and that everyone complaining about semicolon insertion being the worst feature in the language was an idiot. The oft-repeated example from NullUserException's answer didn't sway me because, disregarding indentation, Python behaves the same as JavaScript in that case.

Then one day, I wrote something vaguely like this:

alert(2)
(x = $("#foo")).detach()

I expected it to be interpreted like this:

alert(2);
(x = $("#foo")).detach();

It was actually interpreted like this:

alert(2)(x = $("#foo")).detach();

I now use semicolons.

JavaScript will only1 treat a newline as a semicolon in these cases:

  • It's a syntax error not to.
  • The newline is between the throw or return keyword and an expression.
  • The newline is between the continue or break keyword and an identifier.
  • The newline is between a variable and a postfix ++ or -- operator.

This leaves cases like this where the behaviour is not what you'd expect. Some people2 have adopted conventions that only use semicolons where necessary. I prefer to follow the standard convention of always using them, now that I know it's not pointless.


1 I've omitted a few minor details, consult ECMA-262 5e Section 7.9 for the exact description.
2 Twitter Bootstrap is one high-profile example.

Community
  • 1
  • 1
Jeremy
  • 1
  • 85
  • 340
  • 366
  • 2
    if you lead any lines starting with an open bracket of some kind with a semi-colon, you avoid this case. This and return are treated as two examples of strangeness in javascript semi-colon handling, in actuality they are the only two cases. – Matt Briggs Aug 28 '11 at 18:34
  • 1
    Link to reference #2 is broken. – NPN328 Feb 10 '21 at 11:59
  • Both links in footnotes are broken: the domain expired for `ecma262-5.com` and the GitHub one is 404. – Peter Mortensen Jun 06 '22 at 19:54
8

Aside from the syntactical issues, it is partly cultural. In Python culture any extraneous characters are an anathema, and those that are not white-space or alphanumeric, doubly so.

So things like leading $ signs, semi-colons, and curly braces, are not liked. What you do in your code though, is up to you, but to really understand a language it is not enough just to learn the syntax.

cdarke
  • 42,728
  • 8
  • 80
  • 84
  • >In Python culture any extraneous characters are an anathema huh? ...not, not really. "Flat is better than nested". So this: `x = some_long_function(y); something_else_kinda_verbose(x)` is generally prefered to this: `something_else_kinda_verbose(some_long_function(y))`. (the only reason there's a semicolon in there is that I couldn't figure out how to get a newline in a comment; it'd really be a newline. considering the discussion... ugh.) – jorelli Nov 25 '11 at 19:44
  • I think a better example which destroys my argument might be the `@` used to prefix decorators, or maybe `__` to indicate a variable is "private" (sort-of). I feel that the use of `_` and `__` breaks the zen, then again Guido probably does not. – cdarke Jul 28 '12 at 11:26
8

JavaScript is designed to "look like C", so semicolons are part of the culture. Python syntax is different enough to not make programmers feel uncomfortable if the semicolons are "missing".

  • 1
    While the other observation about JS interpreting them incorrectly are fine, I think **this is the real reason**. – o0'. Aug 28 '11 at 08:18
  • 7
    This argument strikes me as somewhat circular. If not for the semicolons, and perhaps the braces, Javascript wouldn't look much like C at all. – Karl Knechtel Aug 28 '11 at 10:12
7

The answer why you don't see them in Python code is: no one needs them, and the code looks cleaner without them.

Generally speaking, semicolons is just a tradition. Many new languages have just dropped them for good (take Python, Ruby, Scala, Go, Groovy, and Io for example). Programmers don't need them, and neither do compilers. If a language lets you not type an extra character you never needed, you will want to take advantage of that, won't you?

It's just that JavaScript's attempt to drop them wasn't very successful, and many prefer the convention to always use them, because that makes code less ambiguous.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hamstergene
  • 24,039
  • 5
  • 57
  • 72
  • 5
    I don't buy this generalization. Semicolons are a part of the *grammar* of the language, used to disambiguate between different parse trees for the same expression. Look at Jeremy's answer for an example. You can't simply remove semicolons from a C-like language and expect it to work, you have to *change the entire grammar* to ensure it can never be ambiguous without them. – Blindy Aug 28 '11 at 17:23
  • 2
    That's what I said: *NEW* languages are getting rid of them. Not the old ones. What exactly is it you don't buy? – hamstergene Aug 29 '11 at 04:20
5

It is mostly that Python looks nothing like Java, and JavaScript does, which leads people to treat it that way. It is very simple to not get into trouble using semicolons with JavaScript (Semicolons in JavaScript are optional), and anything else is FUD.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matt Briggs
  • 41,224
  • 16
  • 95
  • 126
0

Both are dynamic typing to increase the readability.

Python Enhancement Proposal 8, or PEP 8, is a style guide for Python code. In 2001, Guido van Rossum, Barry Warsaw, and Nick Coghlan created PEP 8 to help Python programmers write consistent and readable code. Reference.

So in JavaScript we have the ECMAScript specification that describes how, if a statement is not explicitly terminated with a semicolon, sometimes a semicolon will be automatically inserted by the JavaScript engine (called “automatic semicolon insertion” (ASI)). Reference.

See this article from Google talking about JavaScript too.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Franz Kurt
  • 1,020
  • 2
  • 14
  • 14