Javascript – How does Python’s handling of line-breaks differ from JavaScript’s automatic semicolons

javascriptpython

Javascript has a feature called Automatic Semicolon Insertion where basically if the parser encounters an invalid token, and the last token before that was a line break, then the parser will insert a semicolon where the linebreak is. This enables you to basically write all your javascript code without semicolons, but you have to be aware of some edge cases, mostly if you have a return keyword and then the value you want to return on a new line.

function test(){
    // This will return 'undefined', because return is a valid statement
    // and  "john" is a valid statement on its own.
    return 
          "john"
}

Because of these gotchas there are dozens of articles with titles like 'Automatic semicolon insertion is Evil', 'Always use semicolons in Javascript' etc.

But in Python no one ever uses semicolons and it has exactly the same gotchas.

def test():
    # This will return 'undefined', because return is a valid statement
    # and  "john" is a valid statement on its own.
    return 
    "john"

Works exactly the same, and yet no-one is deadly afraid of Pythons behaviour.

I think the cases where the javascript behaves badly are few enough that you should be able to avoid them easily. Return + value on a new line? Do people really do that a lot?

What are considered the best practices? Do you use semicolons in javascript and why?

Best Answer

The reason is that in Python, newlines are an unambiguous way of separating code lines; this is by design, and the way this works has been thoroughly thought through. As a result, python code is perfectly readable and unambiguous without any special end-of-statement markers (apart from the newline).

JavaScript, on the other hand, was designed with a C-like syntax in mind, where statements are always terminated with a semicolon. To make the language more tolerant to errors, it tries to guess where extra semicolons should go to make the code correct. Since this was sort of retro-fitted onto the C-like syntax, it doesn't always work as expected (sometimes, the script interpreter guesses wrong), and can make for fairly counter-intuitive code.

Or, arguing in terms of "explicit is better than implicit": In Python, a newline is already completely explicit, while in JavaScript, it is ambiguous, so you add the semicolon to make it explicit.

Related Topic