What is Closures / Lambda in PHP or Javascript in layman's terms?

What is Closures / Lambda in PHP or JavaScript in layman's terms? An example would be useful for my understanding. I assume Lambda and Closures are the same?

+5
javascript closures lambda php
Dec 21 '10 at 16:20
source share
4 answers

Lambda is an anonymous function. Closing is a function that carries its own scope. My examples here will be in Python, but they should give you an idea of โ€‹โ€‹the appropriate mechanisms.

print map(lambda x: x + 3, (1, 2, 3)) def makeadd(num): def add(val): return val + num return add add3 = makeadd(3) print add3(2) 

In the map() call, lambda is displayed, and add3() is the closure.

JavaScript:

 js> function(x){ return x + 3 } // lambda function (x) { return x + 3; } js> makeadd = function(num) { return function(val){ return val + num } } function (num) { return function (val) {return val + num;}; } js> add3 = makeadd(3) // closure function (val) { return val + num; } js> add3(2) 5 
+4
Dec 21 '10 at 16:26
source share

SO already has the answers:

What is lambda (function)?

How do JavaScript closures work?

+4
Dec 21 '10 at 16:29
source share

Anonymous functions are functions declared without a name.

For example (using jQuery):

 $.each(array, function(i,v){ alert(v); }); 

The function here is anonymous, it is created specifically for this call to $.each .

Closing is a type of function (it can be used in an anonymous function or it can be called), where the parameters passed to it are โ€œcapturedโ€ and remain unchanged even outside the scope.

Closing (in JavaScript):

 function alertNum(a){ return function(){ alert(a); } } 

Closing returns an anonymous function, but it should not be an anonymous function.

Continuing the closure example:

 alertOne = alertNum(1); alertTwo = alertNum(2); 

alertOne and alertTwo are functions that will trigger warnings 1 and 2, respectively, when called.

+2
Dec 21 '10 at 16:41
source share

Anonymous functions, also known as closures, allow you to create functions that do not have a specific name. They are most useful as the value of callback parameters, but they have many other uses. Lambda functions allow you to quickly define drop functions that are not used elsewhere.

0
Dec 21 '10 at 16:23
source share



All Articles