Skip to content Skip to sidebar Skip to footer

Why Does Leaving Off A Semicolon Break This Code?

Or put another way, why does semicolon insertion fail, leaving the code below broken. function Foo() { } Foo.prototype.bar = function () { console.log('bar'); } // <-------

Solution 1:

Because it sees the ( on the line below and takes it to mean you want to call the above (using the below function as an argument).

Solution 2:

Think of it like this...

Foo.prototype.bar = function () { // <-- 1. functionconsole.log("bar");
}(function () {    // <-- 2. call the 1. function, passing a function argumentFoo.prototype.la = function () {
        console.log("la");
    };
})();  // <-- 3. tries to invoke the return value of the 1. function, //            but "undefined" was returned.

I don't like using () for IIFE. I prefer other operators.

Foo.prototype.bar = function () {
    console.log("bar");
}

voidfunction () {
    Foo.prototype.la = function () {
        console.log("la");
    };
}();

If we go back to the original, and have the first function return a function, you'll see that one invoked.

Foo.prototype.bar = function () { // <-- 1. functionconsole.log("bar");
    returnfunction() { alert('INVOKED'); }; // 2. return a function

}(function () {    // <-- 3. call the 1. function, passing a function argumentFoo.prototype.la = function () {
        console.log("la");
    };
})();  // <-- 4. tries to invoke the return value of the 1. function,//         which will now call the returned function with the "alert()"

Updated to use a unary operator as suggested by @Lasse Reichstein, as a binary operator will still evaluate its left and right operands, and return the result, which will be used for the assignment.

Post a Comment for "Why Does Leaving Off A Semicolon Break This Code?"