Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self-Invoking Functions in JavaScript

What's the difference between these functions? Thanks for reply!

Function #1

var myQuery = (function() {

  (...)

})();

Function #2

var myQuery = (function() {

  (...)

});
like image 755
Randy Hartmanec Avatar asked Oct 27 '10 16:10

Randy Hartmanec


People also ask

What are self-invoking functions explain with example?

A self-invoking (also called self-executing) function is a nameless (anonymous) function that is invoked immediately after its definition. An anonymous function is enclosed inside a set of parentheses followed by another set of parentheses () , which does the execution. (function(){ console. log(Math.

Why use immediately invoked function JavaScript?

An Immediately-invoked Function Expression is a way to execute functions immediately, as soon as they are created. IIFEs are very useful because they don't pollute the global object, and they are a simple way to isolate variables declarations.

What is self JavaScript?

"self" has no special syntactic meaning, it is just an identifier. Browsers tend to define window. self (just a property of the global window object) = window.

What is JavaScript IIFE example?

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.


2 Answers

In the first case, you're self-invoking a function literal and assigning the value of the invocation to the variable myQuery.

In the second case, you're assigning a reference to the anonymous function that you've defined. Here, myQuery acts like a pointer or a reference to a function.

To better illustrate this.

var myQuery = (function() {
   return "Hello";
})();

In this case, myQuery contains the value Hello. Now if you had:

var myQuery = (function() {
   return "Hello";
});

myQuery contains a reference to the function. If you used console.log in Firebug to output this value, you would see function(). This reference is something you can pass around or even invoke. So:

var myQuery = (function() {
   return "Hello";
});

var value = myQuery();

Now, value will contain Hello. Hope this explains the difference.

like image 84
Vivin Paliath Avatar answered Sep 21 '22 09:09

Vivin Paliath


I'll simplify Function #2 and perhaps that will better show the differences.

var myQuery = function(){ (...) };

In Function #2, you're saying "Assign myQuery a reference to this function." In Function #1, you're saying "Assign myQuery the value of a call to this function."

like image 23
Jesse Hallam Avatar answered Sep 19 '22 09:09

Jesse Hallam