|Written by Ian Elliot|
|Tuesday, 14 January 2014|
Page 2 of 2
A more familiar alternative
Things are even simpler because you don't have to store a reference to a function to pass it to another function or to make use of it.
Anywhere you can use an object reference you can use an object literal.
This last example looks a lot more like the sort of typical use that lambda expression are put to in other languages.
In say C# you could write the same thing using
and the expression (a,b) => a.length-b.length is a lambda expression. Notice that apart from being a little more compact - no need for the keywords function and return - it is more or less the same.
Of course there is nothing stopping you from creating your own functions that accept other functions. As long as you have fully accepted the "functions are just objects" idea you probably don't need to see an example of how to do this but for completeness:
This will simply call any function that you pass to it. If you define:
will call the Hello function and display an alert.
Notice that you have to pass the variable that references the function without accidentally invoking the function.
That is don’t write:
by mistake as this would call the Hello function and then pass its result to the Say function which as a string couldn't be called as a function.
You need to distinguish very clearly between passing a function and passing the result of a function to another function.
Function Invocation ()
You also need to get into the habit of thinking of the () brackets as being the function invocation operator. When ever you use () following an expression it calls the function that is the result of the expression.
For example you can write:
The round brackets at the end of the function definition call the function as soon as it has been defined.
This instant function evaluation can be useful when you want to pass the result of a "lambda expression".
Here we have a lambda expression, the sum function being defined and evaluated in a single step.
The result, 3 in this case is passed to the alert function.
So what to take away -
The only difference between an object and a function object is that a function object has a default method i.e. the code that is usually considered to be the function.
Superficially a function object literal looks a lot like a lambda expression and it can mostly be used in exactly the same way.
This means you can pass functions to other functions store them in arrays and generally make use of them as standard objects.
To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, Facebook, Google+ or Linkedin, or sign up for our weekly newsletter.
or email your comment to: email@example.com
|Last Updated ( Tuesday, 28 October 2014 )|