Kaushik Thanki Kaushik Thanki - 1 year ago 103
AngularJS Question

Is there any difference in this JavaScript code?

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

Answer Source

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.

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download