Friday, December 16, 2022

[FIXED] What is the difference between semicolons in JavaScript and in Python?

Issue

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?


Solution

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.



Answered By - NullUserException
Answer Checked By - Mildred Charles (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.