Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the JavaScript need to start with ";"?

People also ask

What you need to start with JavaScript?

Prerequisites. To learn JavaScript, you must know the basics of HTML and CSS, both of which are extremely easy to learn. For a working knowledge of JavaScript and most web-based projects, this knowledge will be sufficient.

Why JavaScript should be your first language?

Another advantage of learning JavaScript as your first programming language is that you get instant feedback; with a minimal amount of code, you'll immediately see visible results. There's also a huge JS community on sites like Stack Overflow, so you'll find plenty of support as you learn.

Why there's in need to know the basics in HTML CSS and JavaScript before go in the server side language?

HTML and CSS are actually not technically programming languages; they're just page structure and style information. But before moving on to JavaScript and other true languages, you need to know the basics of HTML and CSS, as they are on the front end of every web page and application.


I would say since scripts are often concatenated and minified/compressed/sent together there's a chance the last guy had something like:

return {
   'var':'value'
}

at the end of the last script without a ; on the end. If you have a ; at the start on yours, it's safe, example:

return {
   'var':'value'
}
;(function( $ ){ //Safe (still, screw you, last guy!)

return {
   'var':'value'
}
(function( $ ){ //Oh crap, closure open, kaboom!

return {
   'var':'value'
};
;(function( $ ){ //Extra ;, still safe, no harm

I believe (though I am not certain, so please don't pounce on me) that this would ensure any prior statement from a different file is closed. In the worst case, this would be an empty statement, but in the best case it could avoid trying to track down an error in this file when the unfinished statement actually came from above.


Consider this example:

function a() {
  /* this is my function a */
}
a()
(function() {
  /* This is my closure */
})()

What will happen is that it will be evaluated like this:

function a() {
  /* this is my function a */
}
a()(function() {})()

So what ever a is returning will be treated as a function an tried to be initialized.

This is mostly to prevent errors when trying to concat multiply files into one file:

a.js

function a() {
  /* this is my function a */
}
a()

b.js

(function() {
  /* This is my closure */
})()

If we concat these files together it will cause problems.

So therefore remember to put your ; in front of ( and maybe also a few other places. Btw. var a = 1;;;var b = 2;;;;;;;;;var c = a+b; is perfectly valid JavaScript