Is there any difference in this javascript?

I saw various code that is implemented in two ways. I always use the second (2.). I wanted to know two things here.

  • Is there a difference between the two codes?

  • Which one is best practice (and why), if any?

1.

(function () {
    //some code here, angular code
})();

2.

 (function () {
     //some code here, angular code
 });

Please also offer me a good blog or book in this regard, as I want to learn more. Thanks to everyone in advance.

+4
source share
4 answers

Yes, you are not doing the second.

In the first example, you declare an anonymous function that runs after that without parameters.

In the second example, you simply declare it, but do not run it.

() - , , .

:

    (function () {
        //some code here, angular code
    })();

:

    (function () {
        //some code here, angular code
    });

, , :

    (function (c) {
        // c.log() is same as console.log
        c.log("hello");
    })(console);

: , - .

Edit:

@Osman , IIFE.

, : IIFE, .

+9

- , - .

+3

:

:

    (function () {
        //some code here, angular code
    })();

:

    (function () {
        //some code here, angular code
    });

anonymous function - , .

:

, declare (__function_declaration__), :

    // this is a function declaration:
    function () {
        //some code here
    }

    // this is a function expression
    (function () {
        //some code here
    });

, . , . .

, , jQuery:

    // now jQuery is taking the function expression as parameter
    $(function () {
        //some code here
    });

, () ( - - ):

    // Now the function expression gets executed.
    (function () {
        //some code here, angular code
    })();

IIFE.

. , , , :

    (function (c) {
        // Here c.log() is same as console.log()
        c.log("hello");
    })(console);

. , - .

:

, . IIFE , - , , , .. .

:

, , .

+1
source

The first of these is an IIFE expression (an expression triggered by an immediate call), as others have said, for more information about IIFE checking this repo by Kyle Simpson (author of "You Don't Know JS")

0
source

Source: https://habr.com/ru/post/1669062/


All Articles