Understanding Higher Order functions in Javascript - javascript

I am currently reading Eloquent Javascript Chapter 5. They give the following example which is confusing the hell out of me.
function greaterThan(n) {
return function(m) { return m > n; };
}
var greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
// → true
Can anyone break this down to me as simply as possible. I have huge trouble with callbacks. Especially when it comes to situations like these.

Higher-Order functions basically mean two things:
Functions can take other functions as an argument/input
Functions can return functions
This is what is meant by higher-order functions.
// this function takes a function as an argument
function myFunc(anotherFunc) {
// executes and returns its result as the output which happens to be a function (myFunc)
return anotherFunc();
}
// let's call myFunc with an anonymous function
myFunc(function() {
// this returns a function as you see
return myFunc;
});
As for your example, it demonstrates higher-order functions by returning a function. It also demonstrates the notion of closure.
Closure is closing over a scoped variable, in this case the input argument n.
function greaterThan(n) {
// n is closed over (embedded into and accessible within) the function returned below
return function(m) { return m > n; };
}
// greatherThan10 reference points to the function returned by the greaterThan function
// with n set to 10
// Notice how greaterThan10 can reference the n variable and no-one else can
// this is a closure
var greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
// → true

There's no "callback" involved here. What you've got with the "greaterThan" function is a function that returns another function.
So, you call the function:
var greaterThan10 = greaterThan(10);
Now the variable "greaterThan10" references the function returned by the "greaterThan" function invoked with 10 as the argument.
Then, you log the result of calling that function:
console.log(greaterThan10(11));
The function returned from "greaterThan" is invoked. It compares its parameter to the value of the parameter "n" passed when it was created. Because 11 is in fact greater than 10, the function will return true and that's what'll be logged.

Related

In what scenario would you use a function that returns another function (Javascript)?

Thanks to this question I understand how a function may take two sets of parentheses and how a function may return another function which fires immediately after being returned.
What I do not understand is why this is good to know? How could this be applied to solve a problem?
The example of:
function add(x){
return function(y){
return x + y;
};
}
add(3)(4) === 7; // true
Works fine - sure. But why not just write it like this instead?
function add(a, b) {
return a + b;
}
add(3, 4) === 7; // true
Lets take the same code which you have mentioned.
function add(x) {
return function(y) {
return x + y;
};
}
var adder3 = add(3); //Forming adder3
var op1 = adder3(4) // 7
var op1 = adder3(5) // 9
// Now adder 10:
var adder10 = add(10); //Forming adder3
var op1 = adder10(4) // 14
var op1 = adder10(5) // 15;
Hope you understand!!
Revert me if you need more info on closure.
Your example called as closures
Closures’ Rules and Side Effects
Closures have access to the outer function’s variable even after the outer function returns:
One of the most important and ticklish features with closures is that the inner function still has access to the outer function’s variables even after the outer function has returned. Yep, you read that correctly. When functions in JavaScript execute, they use the same scope chain that was in effect when they were created. This means that even after the outer function has returned, the inner function still has access to the outer function’s variables. Therefore, you can call the inner function later in your program. This example demonstrates:
function celebrityName(firstName) {
var nameIntro = "This celebrity is ";
// this inner function has access to the outer function's variables, including the parameter​
function lastName(theLastName) {
return nameIntro + firstName + " " + theLastName;
}
return lastName;
}​​
var mjName = celebrityName("Michael"); // At this juncture, the celebrityName outer function has returned.​
​​ // The closure (lastName) is called here after the outer function has returned above​
​ // Yet, the closure still has access to the outer function's variables and parameter​
mjName("Jackson"); // This celebrity is Michael Jackson

Closures store references to the outer function’s variables; they do not store the actual value. 
Closures get more interesting when the value of the outer function’s variable changes before the closure is called. And this powerful feature can be harnessed in creative ways, such as this private variables example first demonstrated by Douglas Crockford:
function celebrityID() {
var celebrityID = 999;
// We are returning an object with some inner functions​
// All the inner functions have access to the outer function's variables​
return {
getID: function() {
// This inner function will return the UPDATED celebrityID variable​
// It will return the current value of celebrityID, even after the changeTheID function changes it​
return celebrityID;
},
setID: function(theNewID) {
// This inner function will change the outer function's variable anytime​
celebrityID = theNewID;
}
}​
}​​
var mjID = celebrityID(); // At this juncture, the celebrityID outer function has returned.​
mjID.getID(); // 999​
mjID.setID(567); // Changes the outer function's variable​
mjID.getID(); // 567: It returns the updated celebrityId variable


Reference site : http://javascriptissexy.com/understand-javascript-closures-with-ease/
Functions which return functions are useful when you want similar functions which depend on some parameters.
A real life example: [].sort can be called with a custom comparator function, but it can make sense to define a comparator function to allow more customizations:
function comparator(options) { // Function which returns a function
return function(a, b, tmp) {
if(options.reverse) tmp = a, a = b, b = tmp;
if(options.map) a = options.map(a), b = options.map(b);
if(options.func) return options.func(a, b);
return a < b ? -1 : (b < a ? 1 : 0);
}
}
Then you can use
[1,11,10,2].sort(comparator({map: String})); // [1, 10, 11, 2]
[1,11,10,2].sort(comparator({reverse: true})); // [11, 10, 2, 1]
[1,11,10,2].sort(comparator({func: Function.prototype})); // [1, 11, 10, 2]
if we require a function in certain state with certain value then we can use it inside another function and return that, so that the return function with certain state can be directly used in different scenario.
you can check out various example on closure.
http://javascriptissexy.com/understand-javascript-closures-with-ease/
If you know the first param is always going to be the same, then it will convenient to have it closure, instead of passing it again and again. For simple programs, it may not make sense. But, for programs which handles repetitive params more often, this technique definitely comes handy.
Other than closures you can also use it for pre-processing as a one time job, consider if you had to do something intensive, e.g. generate a million things;
function generateSessionSecrets(lock) {
var secrets = [], i = 1000000;
while (i-- > 0) {
secrets[i] = Math.random();
}
return function(key, i) {
if (key === lock) return secrets[i];
}
}
var chest = generateSessionSecrets('fizz');
chest('fizz', 0); // e.g. 0.2096199430525303
chest('fizz', 1); // e.g. 0.30329699837602675
// ...
chest('fizz', 0); // still 0.2096199430525303
(This is an example of concept, not an example of real security)
there isn't a point to using it immediately. you would use it to create a function to attach it to an event or use as a callback for an asynchronous function. an example might be such:
function factory(param){
return function(result) {
if (result==param) dosomething();
}
}
$('#domobject').click({
param = $('#domvalue').value;
asynch_function(factory(param));
});
Here I've attached a click event to presumably a button. When it is clicked it will retrieve the value of an input and create a function based on it and call an asynchronous function with the newly created function as it's callback. The asynchronous function might be an ajax request. When the asynchronous function completes the function that factory created, the callback, will be called. It will check the return value the asynchronous function passed to the callback against the param specified when the event was attached.
If we move the dom lookup to inside the callback function, then we wouldn't need factory or param, but then it would use the value that is in the input at the time when the asynch function has returned, rather than when the button was clicked which is later and the value might have changed.
Sometimes, you won't be able to obtain a value you need in the context of the callback for other reasons. Or it might just be that you want to abstract out a class of functions so you don't have to retype a slightly different version of it in all the places you use it.

Benefits of using call keyword to call a function in Javascript

In JavaScript, we can call a function in two ways:
function f(message) { ... }
f.call(this, "test");
or just:
f("test")
Except that we can specify the scope in the first case, is there any other advantage to using this syntax over the other one?
You can pass a this object as you like/need. E.g.
[].slice.call("abcdef", 2) === ['c', 'd', 'e', 'f'];
or
var x = {hasOwnProperty:function() { return false; }, key:42};
x.hasOwnProperty('key'); // == false
{}.hasOwnProperty.call(x, 'key'); // true
You should take notice that call is not a keyword, but a method of Function.prototype.
Read:
Function.prototype.call
Function.prototype.apply
Except that we can specify the scope in the first case
You can't "specify scope". Scope is set by how code is written, you can't dynamically change it other than to a limited extent using with. A function's this keyword has nothing to do with scope, it's always resolved as a local variable in the current execution context.
You can also use call (and apply) for partial function application, which is when you create a function that calls another function with some preset arguments. For example:
// Basic add function
function add(a, b) {
return a + b;
}
// Function to create new adders with a preset 'a' argument
function createAdder(a) {
return function(b) {
return add.call(null, a, b);
}
}
// Let's create a function that always adds five to what's passed in
var addFive = createAdder(5);
// Now let's test it
addFive(6); // 11 - it works!

What is the difference in the following JS syntax?

Following are two ways to define BW.Timer. Can someone tell me what the difference is? I am not certain the first is even valid, but if it is valid, what is different about using the myfunc=(function(){}()) syntax?
BW.Timer = (function () {
return {
Add: function (o) {
alert(o);
},
Remove: function (o) {
alert(o);
}
};
} ());
And...
BW.Timer = function () {
return {
Add: function (o) {
alert(o);
},
Remove: function (o) {
alert(o);
}
};
};
The first is the return-value of the immediately-invoked function. The second is a function. It essentially comes down to what the difference is between these:
var f = (function() { return 0; })();
var f = function() { return 0; };
Since the first function is called immediately, the value of 0 is given to the variable f. The first f is not a function. However, the second f we must call in order to get the value:
f(); // 0
It follows that in your example, the first BW.Timer is the object literal itself and the second is a function returning an object literal. You must call the function in order to get to the object:
BW.Timer().Add(x);
Why use the first then?
You might ask yourself why one would use a syntax like a = (function() { return {}; })() instead of a = {}, but there's a good reason. An IIFE (Immeditately-Invoked Function Expression), unlike a regular function allows the emulation of static variables (variables that maintain their value through a single instance). For example:
var module = (function() {
var x = 0;
return { get: function() { return x },
set: function(n) { x = n }
};
})();
The above a text-book example of the Module Pattern. Since the function is called right away, the variable x is instantiated and the return value (the object) is given to module. There's no way we can get to x other than by using the get and set methods provided for us. Therefore, x is static, meaning its variable won't be overridden each time you use module.
module.set(5);
module.get(); // 5
On the other hand, let's see an example where module is declared as a function instead:
// assume module was made as a function
module().set(5);
module().get(); // 0
When we call module() the x variable is overridden each time. So we're effectively using different instances of module and x each time we call module.
The difference is rather large.
In the first case, BW.Timer is executed when it is first encountered, and that is the static version assigned to BW.Timer. In that instance, BW.Timer.Add(1) may be used. Each call to BW.Timer will be the same object.
In the second case, BW.Timer is not executed when first encountered, and instead is a function referece which must be invoked BW.Timer(). For Add to be used, this must be the case BW.Timer().Add(1). Also, you can issue var timer = new BM.Timer();. Each instance of BW.Timer() will be unique here.
In the first example BW.Timer references an object that the self-executing function returns, while in the second example it references a function object, in other words it's a function that can be executed BW.Timer().

Javascript anonymous function use-case

I am working my way through Eloquent Javascript and I came across a code snippet that looks like this:
function greaterThan(x) {
return function(y) {
return y > x;
};
}
var greaterThanTen = greaterThan(10);
show(greaterThanTen(9));
Is there any real use-case to defining the function like this with an anonymous function inside of it? Wouldn't it be much simpler to do this:
function greaterThan(x,y){
return x > y;
}
var greaterThanTen = greaterThan(9, 10);
any ideas/comments/suggestions would be very helpful.
This is an example of a "closure". Basically, a call to greaterThan() gives you a function. That function, instead of just a mere function, carries with it the value of x - it's like embedding the value of x permanently into the function.
function obj(x) {
//"public interface"
//only these are exposed (inc and getX). x is private.
return {
inc: function() {
return ++x;
},
getX: function() { //a getter function to retrieve private x
return x;
}
}
}
//the value 10 is "embedded" to the returned object
var myobj = obj(10);
//every call to inc increments that "embedded" value
console.log(myobj.inc()); //11
console.log(myobj.inc()); //12
console.log(myobj.inc()); //13
//but you can never access the variable of `x` directly without a "getter"
console.log(myobj.getX());​
Closures are one of the great features of JavaScript. One of it's great uses is to emulate private variables.
The first example you are combining functions.
Of course you can write in different ways but the idea of greaterThanTen in the first example is be something different. For example you can pass this to a filter
var a = [ 1 , 10, 100 , 9, 43 ];
function greaterThan(x) {
return function(y) {
return y > x;
};
}
var greaterThanTen = greaterThan(10);
a.filter(greaterThanTen);
returns [100, 43]
It is functional programming. There is many advantages.
Unless I missed something, the first code returns a function.
The second one returns the result.
That's not a particularly good use case. A better use case for anonymous functions is callbacks, as in: you wish to execute function #2 once function #1 is completed.
function a(param1, param2, callback) {
//work on param1 and param2 here
callback.call(); //triggers the callback function
}

how to use function(1)(2) in javascript? and how does it work?

I understand calling function(1) but not function(1)(2), how does it work?
also possible for function(1)(2)(3)(4) too?
In this case you are supposing that function(1) returns a function, than you are calling this new, anonymous function with an argument of 2.
See this example:
function sum(a) {
return function(b) {
return a+b;
}
}
// Usage:
window.alert(sum(5)(3)); // shows 8
var add2 = sum(2);
window.alert(add2(5)); // shows 7
window.alert(typeof(add2)); // shows 'function'
Here we create a function sum that takes one argument. Inside the function sum, we create an anonymous function that takes another argument. This anonymous function is returned as the result of executing sum.
Note that this anonymous function is a great example of what we call closure. A closure is a function that keeps the context in which it was created. In this case, it will keep the value of the variable a inside it, as did the example function add2. If we create many closures, they are independent as you can see:
var add3 = sum(3);
var add4 = sum(4);
window.alert(add3(3)); // shows 6
window.alert(add4(3)); // shows 7
Furthermore, they won't get "confused" if you have similarly named local variables:
var a = "Hello, world";
function multiply(a) {
return function(b) {
return a * b;
}
}
window.alert(multiply(6)(7)); // shows 42
var twoTimes = multiply(2);
window.alert(typeof(twoTimes));
window.alert(twoTimes(5));
So, after a call to sum(2) or multiply(2) the result is not a number, nor a string, but is a function. This is a characteristic of functional languages -- languages in which functions can be passed as parameters and returned as results of other functions.
You have a function that returns a function:
function f(n) {
return function(x) {
return n + x;
};
}
When you call f(1) you get a reference to a function back. You can either store the reference in a variable and call it:
var fx = f(1);
var result = fx(2);
Or you can call it directly:
var result = f(1)(2);
To get a function that returns a function that returns a function that returns a function, you just have to repeat the process:
function f(n) {
return function(x) {
return function(y) {
return function(z) {
return n + x + y + z;
}
}
};
}
If your function returns a function, you can call that too.
x = f(1)(2)
is equivalent to:
f2 = f(1)
x = f2(2)
The parenthesis indicate invocation of a function (you "call" it). If you have
<anything>()
It means that the value of anything is a callable value. Imagine the following function:
function add(n1) {
return function add_second(n2) {
return n1+n2
}
}
You can then invoke it as add(1)(2) which would equal 3. You can naturally extend this as much as you want.

Categories