First class functions in Javascript - javascript

I am reading an article on SitePoint (https://www.sitepoint.com/javascript-closures-demystified/) and there is an example of a first class function:
var foo = function() {
console.log("Hello World!");
};
var bar = function(arg) {
return arg;
};
bar(foo)();
The syntax of the last line looks puzzling to me, and I would have written it as:
bar(foo());
Does anyone know if either syntax is ok, or if there is a good reason for writing it the way the article wrote it? If so, please explain what that reason is.
Thanks,
William

Does anyone know if either syntax is ok,
There are completely different.
bar(foo)() calls bar, passing it foo as an argument, gets the return value of bar and then calls that return value as a function.
bar(foo()) calls foo, gets the return value of foo, then calls bar, passing it the return value of foo as an argument.
there is a good reason for writing it the way the article wrote it
It's a completely contrived example. There's no practical reason to involve bar in this at all. It is just showing that you can pass a function about like any other value (which your version doesn't do).

The term "first class functions" can typically be thought of as the ability to pass functions around the same way you would variables.
The last example is taking foo, which is a function, and passing it into bar(), another function. bar() returns yet another function and that is being called immediately after, hence the extra () at the end. So the way the example was written was not just a stylistic approach; it is showing how functions can be passed around, even into other functions.

bar(foo)();
Calls the function bar, using foo (a function, not the return value of the function) as the argument. Since bar returns the argument, bar ends up returning a function. Adding () at the end causes the returned function to be executed.
bar(foo());
Calls the function bar, using the return value of foo() as the argument
The reason why the code example shows a function being passed as an argument to another function, and being returned from the function is to showcase that functions are objects and can be passed around like one.

The two are fundamentally different and would achieve different things. Let's look at both.
bar(foo)();
This passes a reference to the function bar as the only argument to the function bar, which promptly returns the passed function as the return value, which is then executed via the final ().
Essentially, it's a laborious way of executing foo.
bar(foo());
This first executes foo and passes the return value - which is nothing - as the only argument to bar. Nothing further happens.

The result will be the same, but what the two syntax do are different. When writing bar(foo)();, bar returns a function and then you call this function. It means:
arg in the body of the bar method hold a reference to foo;
bar is executed before foo;
bar returns a function.
Writing bar(foo()), you first call foo and then pass its result to bar. It means:
arg in the body of the bar method holds a reference to the string "Hello World"
foo is called first
bar returns a string

When you write foo, you are referencing the function foo, not the value that this function returns. The function is not executed.
When you write foo(), you are executing the function and returning it's value.
So, when you say bar(foo)(), you are passing a function foo as an argument to bar. Since bar returns any argument it receives, this time it returns the function foo, and then it is being executed.
To simplify, this is what is happening:
var foo = function() {
console.log("Hello World!");
};
var bar = function(arg) {
return arg;
};
var returnFromBar = bar(foo);
returnFromBar();

Related

Returning same method being called

I have following code, I am expecting alert('baz') but it is not working
var foo = function () {
function foo() {
alert('foo');
}
foo.baz = function () {
alert('baz');
}
}
foo().baz();
However If I return foo at the end it works
var foo = function () {
function foo() {
alert('foo');
}
foo.baz = function () {
alert('baz');
}
return foo;
}
foo().baz(); // output:baz
why first one not working and why second is working and what is purpose inner foo??
Because chaining method needs to be returned something. So, in your code you are correctly returning the foo and then it's getting called.
The first one is not working, because the "foo" method is not a void, so it expects a return value. Without a return value, the call to the method will fail. I advice you to trace both of the calls in developer tools, breakpoint each and trace step by step the chain of events.
As for your second question, The purpose is simple, to give foo additional functionality. Usually you won't use nested foo, it's a bad practice, but a prototype. As with an account method. It contains first name, last name and account number, then a prototype of the method is created in order to create withdraw and deposit methods for the specific account.
It's almost identical to working with polymorphic objects in C# or JAVA. instead using override, you use prototype, or in the case of the code above, nested "foo".
In your code you are assigning the function to a variable and not normally. The variable name can be used by the code inside the function to refer the function itself, but the code outside the function can not see it at all.
When you call the function like foo().baz();
it will first call the foo() function and will need a return value (in this case a function referer variable). Then according to the referer variable name it will call the baz() inside the foo(). So to call the function baz() inside foo(), you need to access function first.

Why can we subsitute "foo" for "function (x) { return foo(x); }"

I was looking for lesser knows facts about JavaScript and I came across this piece, can anyone explain why the below code
function (x) { return foo(x); }
can be substituted with
foo
Tried to figure this out with the little knowledge of JavaScript which I had, but I didn't find the reason. Can anyone explain it?
Because
var bar1 = function (x) { return foo(x); };
var bar2 = foo;
And then
bar1(5);
bar2(5);
The first one will execute a function that will call foo(5), the second one will call foo(5) directly. Same end result.
The first is a function that takes one argument and returns whatever the result of foo with that argument is. The second is a function which takes one argument (presumably) and returns whatever the result of foo with that argument is (because it is the foo function).
The long version is just a wrapper around foo which doesn't add anything.
function(x){return foo(x);} actually is a nameless function which passes x to the function foo. The nameless function will return the result of foo(x) on the line return foo(x)
which is the same as calling foo(x) at the first place not form inside another function.
This code snippet assumes that foo is already a function in the current scope.
When you want to pass foo as a callback, you can do so directly:
function ITakeACallback(callback) {
callback(42); // and call it
}
ITakeACallback(foo);
So what you did here was pass to ITakeACallback an argument that happens to be a callable function; ITakeACallback indeed calls it.
Of course we can pass any callable function:
ITakeACallback(function(x) { return foo(x); });
This time we passed a function that accepts an argument, calls foo with that argument and returns the result. This is a roundabout way of calling foo directly, but the end result is the same.

Syntax of Closures

function makeIncreaseByFunction(increaseByAmount) {
return function (numberToIncrease) {
return numberToIncrease + increaseByAmount;
};
}
makeIncreaseByFunction(3)(10);
Updated for Clarity
Can somebody explain why the (3)(10) is written the way it is? I understand that 10 is being supplied as an argument to the inner function, but why is syntactically notated like this? If we had three nested functions, would the arguments always be written in order as in (3)(10)(20)?
With intermediate variable:
var increaseBy3 = makeIncreaseByFunction(3);
var foo = increaseBy3(10);
Without intermediate variable:
var foo = makeIncreaseByFunction(3)(10);
In both cases, the first invokation passes the argument 3 to makeIncreaseByFunction, and as a result it returns the inner function that has closed over increaseByAmount with the value of 3. Whether you create a variable for the intermediate function returned by makeIncreaseByFunction, or just invoke it directly, it does the same thing.
Can you explain a little bit more detail about how in var foo = makeIncreaseByFunction(3)(10); the 10 is getting to the inner function? It just looks syntactically different from how arguments usually get passed in Javascript to me. – ggg
makeIncreaseByFunction(3) returns a function, specifically the "inner function" defined inside makeIncreaseByFunction. As will all functions, you call it with the function ( arguments ) syntax. You can write it like this if it makes more sense to you this way:
( makeIncreaseByFunction(3) )(10)
What happens here is makeIncreaseByFunction(3) gets called first and returns the ⟪inner function⟫, and then we call ⟪inner function⟫(10).
If you were evaluating this by hand (I think this is what you meant by "syntactically"), you could think of it happening step-by-step like this:
// Original invocation
var foo = makeIncreaseByFunction(3)(10);
// Substitute the definition of makeIncreaseByFunction
var foo = (function (increaseByAmount) {
return function (numberToIncrease) {
return numberToIncrease + increaseByAmount;
};
})(3)(10);
// Apply the parameter 3
var foo = (function (numberToIncrease) {
return numberToIncrease + 3;
})(10);
// Apply the parameter 10
var foo = 10 + 3;
// Final result
var foo = 13;
Note: If you want to be technical, all we're doing here is two Beta reductions—but unless you have background with the Lambda Calculus that will probably confuse you more than it will help you!
makeIncreaseByFunction(3) would return function so the syntax for then calling it with 10 would be makeIncreaseByFunction(3)(10).
This is easy to understand as if you have a function foo (imagine that the return of makeIncreaseByFunction(3) is such a function, they are evaluated identically), you would then call it with 10 using foo(10).
As for how the value of 10 is being 'passed', this is the wrong way to thing about things.
You must realise that in Javascript functions are first class objects.
Instead of passing the value to the inner function, you are creating a function that does what you want and then calling it with the outer argument.
It is the same as using a variable to add within a function in a non-functional language except functions can be dynamically created at runtime and the values of any variable in their definition can be set influencing their internal consistency.
The closure refers to the fact that the created function is a black-box which hides the variable used to initialize it, despite still using that variable to increment the value it is called with.
var increaseBy3 = makeIncreaseByFunction(3); is the exact same as (disregarding the local storage for the variable increaseByAmount):
var increaseBy3 = function (numberToIncrease) {
return numberToIncrease + 3;
};
So of course now you can call increaseBy3(10) and get 13. increaseBy3 just references as anonymous function which returns its first argument plus 3.

Setting a variable equal to a function without parenthesis? [duplicate]

This question already has answers here:
What is the difference between a function call and function reference?
(6 answers)
Closed last year.
I was following a tutorial on AJAX, and the person making the video did something strange. At least I hadn't seen it before. They set an object property equal to a function name, but without the familiar (). He later went on to define the function. Code is provided below for context. Anyway, what does it mean to set something equal to a function without the parameters? That line of code is indeed running the function that is named that as you can see below.
xmlHTTP.onreadystatechange = handleServerResponse;
There's a function called "handleServerResponse()", that this line actually runs. I can post it, but I think it's irrelevant. It's just a normal function function handleServerResponse(). Any explanation would be greatly appreciated!
Thanks!
~Carpetfizz
EDIT: Adding () to the end of that line, creates errors, as well as changing it.
What they're doing there is referring to the function without calling it.
var x = foo; // Assign the function foo to x
var y = foo(); // Call foo and assign its *return value* to y
In JavaScript, functions are objects. Proper objects. And so you can pass references to them around.
In that specific case, what they're doing is setting up handleServerResponse as the callback that the XHR object uses when the ready state changes. The XHR object will call that function during the course of doing the ajax request.
Some more examples:
// Declare a function
function foo() {
console.log("Hi there");
}
// Call it
foo(); // Shows "Hi there" in the console
// Assign that function to a varible
var x = foo;
// Call it again
x(); // Shows "Hi there" in the console
// Declare another function
function bar(arg) {
arg();
}
// Pass `foo` into `bar` as an argument
bar(foo); // Shows "Hi there" in the console, because `bar`
// calls `arg`, which is `foo`
It follows on naturally from the fact that functions are objects, but it's worth calling out specifically that there's no magic link between x and foo in the above; they're both just variables that point to the same function. Other than the fact they point to the same function, they're not linked in any way, and changing one (to point at another function, for instance) has no effect on the other. Example:
var f = function() {
console.log("a");
};
f(); // "a"
var x = f;
x(); // "a"
f = function() {
console.log("b");
};
f(); // "b"
x(); // "a" (changing `f` had no effect on `x`)
When the state of the request changes (for example when the browser received the complete answer), the browser will call a function stored in the onreadystatechange property of the xmlHttpRequest. This call will be something like
xmlHTTP.onreadystatechange();
which will be just equivalent to
handleServerResponse();
To decide what function will be called, you assign this function (not the returned value of this function) to this property using the line you show.
This is possible because JavaScript is a language where functions are said first class : they may be property values just like objects, strings, etc.
It means you are assigning the variable a reference to that function. The reference then can be used to call the function instead. Something like this...
function foo(){
alert("I am inside foo");
}
var bar = foo; // bar now points to foo
// Call foo
foo();// alerts "I am inside foo";
// Call bar which is pointing to foo
bar();// alerts "I am inside foo";

Javascript function syntax needs explanation

return this.foo("abc",function(){
//do something
});
Can some one tell me what does the above line do?
THanks
It grabs a reference to this, which might be the DOM Window, a DOM element, or any other JavaScript object depending on how and where the above code is being run.
It (skipping ahead) prepares a new anonymous Function that //does something.
It attempts to invoke a method foo on object this, passing in two parameters "abc" and said anonymous Function.
Very often when you see code that passes along an anonymous function (e.g. function(){ ... }), it is in fact holding on to that function in order to execute it not right away but at some later point in time, such as in response to a click event or a timer.
It calls the function referenced by this.foo and passes two parameters: The string "abc" and an anonymous function function(){ //do something}. It then returns the result.
It is equivalent to:
var a = "abc";
var b = function(){
//do something
};
return this.foo(a, b);
Functions are first class objects in JS so you can pass them around like any other value.
I recommend to have a look at the MDC JavaScript guide.
looks like this.foo() is a function that returns something. so the return value is, what this.foo() returns.
calls an instance method that gets as parameters a string and a function.
It will return (yeah, like it is in English) the returned result of a function this.foo(...) (in the most simple form, ithe function this.foo(...) return "something" then the code will return "something"). The function this.foo("abc", function(){...}); is itself a function which receives 2 arguments: A string "abc" and a function(). The function this.foo will do something and return "something" to return by the main function.
[x]

Categories

Resources