The problem of running order of javascript function

  • 1
    function a() {
        console.log("1")
    }
    a()
    (function () {
        console.log("2")
    })();

after running

clipboard.png

  • 2
    a()
    function a() {
        console.log("1")
    }
    (function () {
        console.log("2")
    })();

if you do this, you won"t get an error, but of course you won"t get an error if you delete the function that executes immediately.
what is the reason for this?

Feb.27,2021

add a semicolon

function a() {
        console.log('1')
    }
    a();
    (function () {
        console.log('2')
    })();

the semicolon is automatically inserted in the wrong position. It should be parsed as follows. Just add a semicolon a (); .

   function a() {
        console.log('1')
    }
   a()(function () {
        console.log('2')
    })();

is missing a semicolon.


standardize writing

function a() {
    console.log('1')
};
a();
(function () {
    console.log('2')
})();

because the semicolon is missing, followed by parentheses, the first one is identified as

 a()(function () {
        console.log('2')
    })();

so an error is reported (in this case an is expected to return a function), and then call with an anonymous function as an argument and then return a function before execution.

Menu