user6330767
user6330767

Reputation:

Why a semicolon is necessary here?

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.

Upvotes: 1

Views: 109

Answers (2)

Pabs123
Pabs123

Reputation: 3435

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.

Upvotes: 3

Barmar
Barmar

Reputation: 780673

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.

Upvotes: 6

Related Questions