JavaScript Jems - Lambda Expressions |
Written by Mike James | ||||
Thursday, 13 July 2023 | ||||
Page 3 of 3
Immediate Invocation ( )You need to get into the habit of thinking of the round brackets () as being the function invocation operator. Whenever you use () following an expression it calls the function that is the result of the expression. For example, you can write: Say=function(t){ t(); }(Hello); and the round brackets at the end of the function definition call the function as soon as it has been defined. This is usually called an "Immediately Invoked Function Expression" or IIFE and is very useful and used a lot in idiomatic JavaScript in connection with anonymous function and arrow functions. This instant function evaluation can be useful when you want to pass the result of a "lambda expression", for example: alert(function(a,b){return a+b;}(1,2)); or: alert(((a,b)=>{return a+b;})(1,2)); Here we have a lambda expression, a sum function, being defined and evaluated in a single step. The result, 3 in this case, is passed to the alert function. Although this example isn’t particularly useful it does become useful when combined with other JavaScript features such as closure. For example, suppose we have a function that needs to access a private variable: var myPrivate=0; function myFunction(){ myPrivate++; return myPrivate; } The variable might be called myPrivate, but it is accessible from any other code that can call myFunction. To make it really private you have to wrap it in another function and immediately invoke it: var myFunction = (function () { var myPrivate = 0; return function () { myPrivate++; return myPrivate; }; })(); This looks complicated, but you can see that the outer anonymous function returns a reference to: function () { myPrivate++; return myPrivate; }; which is the previous function, but now myPrivate is in its execution context and hence part of the closure. The outer function is immediately executed with the sole idea of creating the closure. Enclosing a function within another function and using immediate execution is an idiomatic way of creating private resources via closure. The introduction of arrow functions to provide lambdas is is an odd jem because it tackles a problem JavaScript had already solved and appears to be an addition just to “keep up” with the other languages. Arrow functions don’t make JavaScript worse, and they can be more expressive, but overuse can make code look cryptic. They could be used in many of the examples in this book, but functions or anonymous functions are preferred because they look easier. Now available as a book from your local Amazon.JavaScript Jems:
|
||||
Last Updated ( Monday, 17 July 2023 ) |