Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone explain the difference between closure and anonymous functions?

Tags:

javascript

I am relatively new to Javascript. I understand the concept of anonymous functions - but closures seem less clear. The similarity between the two (in my mind atleast), is confusing.

Could someone explain the difference? (preferrably, with some code snippet, to illustrate the points clearer).

like image 355
Stick it to THE MAN Avatar asked Jan 25 '10 09:01

Stick it to THE MAN


People also ask

Is a closure the same as an anonymous function?

Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class.

What is the difference between closures and functions?

Difference between Function and ClosureFunction is declared using func keyword whereas Closure doesn't have func keyword. Function has always name but Closure doesn't have. Function doesn't have in keyword but closure has in the keyword.

Are all closures anonymous functions?

An anonymous function is just a function that has no name; nothing more. A closure is a function that captures the state of the surrounding environment. An anonymous function does not necessarily need to create a closure, and a closure is not created only for anonymous functions.


3 Answers

The important difference is that a closure captures the scope it was defined in.

In other words, a closure may access variables and their state even though they belong to the closure's parent scope (e.g. the function the closure was created in). This allows closures to capture and "transport" application state around your program.

An anonymous function cannot do that; its reach is limited to variables defined inside its body and signature (i.e., its parameters).

EDIT: Just to clarify: In JavaScript it is especially unclear since there is no language construct called closure. You'd still use an anonymous function for that. I was only referring to the conceptual difference.

like image 108
Matthias Avatar answered Nov 15 '22 12:11

Matthias


An anonymous function is one which does not have any name to it, rest is same as the normal functions in Javascript. Here is an ex. Case 1: This is just some normal/regular javascript function

var sayHello = function iWillSayHello(name){
     var fullName = "Hello, " + name; 
     console.log(fullName);
}
sayHello("ABC");    // prints--->  Hello, ABC

Case 2: This is Annonymous function, It is the same function with the same behavior as above,

var sayHello = function(name){
     var fullName = "Hello, " + name; 
     console.log(fullName);
}
sayHello("ABC");    // prints--->  Hello, ABC

Case 3: If(I think) by "anonymous function" you mean IIFE(Immediately Invoked Function Execution), that is this,

(function(name){
     var fullName = "Hello, " + name; 
     console.log(fullName);
})();     // prints--->  Hello, ABC

The difference here is, In "Case 1" and "Case 2" you have to call the function explicitly, BUT in "Case 3" it is invoked automatically (i.e. with "()" at the end you are calling it as it is declared). It will be called as compiler reaches that line.

Clouser, on the other hand, is a function inside a function. What makes a Clouser a special in js, is it still can access the values of the variable from the "local scope" of the outer function even if the outer function has returned.

Clouser = function + outer context

here is a simple example,

function outerSayHello(firstName){
    var fullName = firstName;
    function innerSayHello(lastName){
         console.log("Hello, ", fullName + " " + lastName);
    }

    return innerSayHello;
}

console.log("1-------------------------");
var sayHello = outerSayHello("A");
sayHello("B");
//Hello,  A B

console.log("2-------------------------");
var sayHello1 = outerSayHello("A1");
sayHello1("B1");
//Hello,  A1 B1

console.log("3-------------------------");
sayHello("b");
//Hello,  A b

console.log("4-------------------------");
sayHello1("b1");
//Hello,  A1 b1

console.log("5-------------------------");
outerSayHello("ABC")("XYZ");
//Hello,  ABC XYZ

to better understand these let's console the sayHello variable

console.log("6-------------------------",sayHello);
/*
  innerSayHello(lastName){
         console.log("Hello, ", fullName + " " + lastName);
    }
*/

What it means is sayHello variable has pointer/reference to the innerSayHello function. And because innerSayHello is relying on fullName variable, it will still be maintained on the heap, and fullName and innerSayHello still be on the stack even after outerSayHello returns. So in the heap, it will create multiple references for fullname and innerSayHello.

like image 21
niranjan_harpale Avatar answered Nov 15 '22 11:11

niranjan_harpale


Have you seen this article? http://www.jibbering.com/faq/faq_notes/closures.html

This could also be good as a starting point: http://www.javascriptkit.com/javatutors/closures.shtml

like image 32
naivists Avatar answered Nov 15 '22 13:11

naivists