What does the semicolon at the beginning of the line mean?

Asked

Viewed 290 times

11

I was going through a code and I found the following excerpt:

;(function ($, window, document, undefined) {
    //...
})(jQuery, window, document);

Note that at the beginning of the first line there is the character ";" (semicolon).
What is the semicolon function at the beginning of the line?

1 answer

10


The semicolon function at the beginning of the line is to correctly concatenate a new code when the previous one does not include ";" at the end.

var n = a + b 
(c + d).print() 

Without the comma, the second line would have been interpreted as a function call.
The system would interpret it as follows:

var n = a + b(c + d).print();

Note that the variable "b" would be interpreted as a function, returning the following error:

ReferenceError: b is not defined

In conclusion, it is good practice to always finish an instruction with ";", but when a line starts with parentheses it is also good practice to precede it with the ";", especially when we need to change third party code.

;(c + d).print()
  • 2

    "Concluindo, quando uma linha começar com parênteses é boa prática precede-lo com o ";"." No. Good practice is to do as the whole world does (see Jslint and Jshint), and to put the semicolon in the right place, which is at the end of the expression immediately preceding that beginning with parentheses. I recommend reading Maintanable Javascript, by Nicholas C. Zaka.

  • @Renan knows the book. Of course it is good practice to finish the instruction with the ";", but I came across this in some codes even containing the ";" at the end of the instruction. Anyway I changed the conclusion.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.