Search code examples
javascriptsyntaxautomatic-semicolon-insertion

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.


Solution

  • 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.