Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference in this JavaScript code? [duplicate]

I have seen various code which is implemented in following two way. I always use the second one (2.). I wanted to know two thing here.

  1. Is there any difference between these two codes?

  2. Which one is the best practice (and why) if any?

1.

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

2.

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

Please also suggest me some good blog or book in this regards as I wants to learn in more detail. Thank you all advance..

like image 521
Kaushik Thanki Avatar asked Dec 11 '22 13:12

Kaushik Thanki


1 Answers

Yes, you are not executing the second one.

In the first example, you are declaring an anonymous function, which gets run afterwards with no parameters.

In the second example, you are just declaring it, but not running it.

() is what makes it run, in this case by passing it no parameters.

This one executes the anonymous function:

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

This one doesn't execute it:

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

For example, if you have a parameter, you can pass it like so:

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

Note: I've added the parameter example because it's less obvious without any parameter.

Edit:

As @Osman has just pointed in the comments, the first one is known as IIFE.

This pattern is so common, a few years ago the community agreed on a term for it: IIFE, which stands for Immediately Invoked Function Expression.

like image 164
zurfyx Avatar answered Mar 17 '23 06:03

zurfyx