Why a semicolon is necessary here?

109 Views Asked by At

I realise in the following JavaScript code, we need to add a ; just after $('#myButton').click(function() {}) to let $('.lala').myFunction() to be called.

$('#myButton').click(function() {})

(function ($) {
    $.fn.myFunction = function (opt) {
      alert("inside myFunction")
    }
})(jQuery);

$('.lala').myFunction()

JSBin

Why ; makes a big difference here? I thought in most of the cases ; between statements can be omitted in JavaScript.

2

There are 2 best solutions below

0
On BEST ANSWER

Because a function call can return another function. Without the semicolon, the parentheses around the IIFE are interpreted as being the argument list to the function that .click() might return, so it's treated as if you'd written:

$('#myButton').click(function() {})(function ($) {
    $.fn.myFunction = function (opt) {
      alert("inside myFunction")
    }
})(jQuery);

Just get out of the habit of depending on automatic semicolon insertion, since the results are sometimes not obvious. If you always put semicolons after your statements, you won't get surprises and don't have to worry about obscure cases like this.

0
On

The absence of a semicolon here is causing the interpreter to think you are trying to pass the second function as an argument of the firs and then trying to call the result of the first function call as a function.

It's basically doing this:

$('#myButton').click(function () {
    //...
}(function () {
    //...
})(jQuery);

The second function will fail. This is one of the classic examples of why it's great practice to always put semicolons after your statements, as it can create very ambiguous cases. There's really no reason not to.