functions returned from other functions in javascript - javascript

I am new learner of Javascript and I got stuck in "functions returned from other functions".
The code is as below.
var createScream = function(logger) { return function(message) {
logger(message.toUpperCase() + "!!!")
}
}
const scream = createScream(message => console.log(message))
scream('functions can be returned from other functions')
scream('createScream returns a function')
scream('scream invokes that returned function')
Console output:
"FUNCTIONS CAN BE RETURNED FROM OTHER FUNCTIONS!!!" "CREATESCREAM
RETURNS A FUNCTION!!!" "SCREAM INVOKES THAT RETURNED FUNCTION!!!"
Question: why it will work this way? what is the process of executing?
Does function scream have any parameter? how does it work?
This may be very easy, I searched but no clear explanation.
Can someone please give me a hint or explain the whole execution process in details?
Thanks in advance!

First, Higher order functions are not about functional languages. Functions that operate on other functions i.e. taking a function as an argument and returning another function, are called higher order functions.
Your snippet:
You created an anonymous function with argument logger, which returns another anonymous function and bind that to variable createScream.
Then you called createScream with a function as an argument. storing the returned value in const scream. At this time you are returned a function with argument logger being the fat arrow function you passed.
Now you called scream with strings. Remember scream is also a function because in the earlier step the function call returned another function. That function has access to logger argument passed to the outer function. This is an example of closure.
When you call scream with strings. The returned function is called which is logging the message in uppercase plus !!!.
It will take sometime to get what is happening here, If you have limited programming experience. Read about higher order functions, lexical scope, closure.

In JavaScript and other functional languages, you will hear the term that functions are "first-class citizens" meaning that functions can be passed around as values or referenced by other functions.
It's normal for this to take a bit of time to grok, but try to walk through your code step by step and you'll get it:
The createScream function accepts a function as input (logger)
The createScream function then returns another function that accepts its own input (message)
The returned function uses the original input function (logger) as well as the second input (message)
And consider the execution order in usage as well:
scream invokes createScream with a console.log function
now when you invoke scream with a message, that message will first be changed as per the definition in createScream
then once the message is changed, it is invoked by the logger function console.log

Related

Why there isn't parentheses for methods inside of promises?

Why there is no parentheses for console.log inside of then block of promise?
How does it know that what should it log?
const Category = require('./models/category');
const cat = Category.find({}).then(console.log);
It's passing a function reference as a callback. console.log refers to a function to be called when the promise resolves as opposed to actually calling console.log.
Functions are first-class objects in JavaScript. They can be passed around. Just like you would do then(x => console.log(x)). If you call it before-hand, it will be necessarily evaluated before (and its return value passed):
promise.then(console.log()) // Called immediately, undefined passed to then
Note that it's not exactly the same as then(x => console.log(x)). Any context is lost because the callee has no way to recover that from just a function reference. Though this doesn't have an effect here AFAIK.
This is a reference to the function that will be called after Category.find(). The value passed to it will be the result of the find.
Calling console.log() inside the then callback would output nothing in the console. Usually, you pass an anonymous or arrow function to the callback argument, but since console.log can pretty much have anything as a parameter, you just have to pass the name of the function so the Promise can execute it later.

Javascript Function Expressions

I have recently been trying to learn javascript and have a couple of questions.
When you create a function expression:
var greet = function(){
console.log('Hi');
}
Is that creating a function object and having the variable "greet" point to that function object in memory?
My second question if you have a function like this:
function log(a){
console.log(a);
}
Then you make a call to that function:
log(greet); //greet is the function expression declared above.
So I know that when a function object is created there are two properties that are given to the object. The name (if provided, otherwise anonymous) and a code property which stores the code contained inside the parentheses of the function. Now I am a little confused on where the parameter "a" in the log function gets attached to in a function object. Is "a" just another property of the function object log and it simply just points to the memory address of anything that is passed into the log function? Where in this case it was a function expression called greet. Any input would be appreciated. Thank you!
When a function is called as in:
log(greet)
then the identifier log is resolved in the current execution context and, if not found, is searched along the scope chain, ending at the global execution context. If not found, an error is thrown.
In this case, log has been defined using a function declaration so it exists in the global scope so is found. Its value is checked to make sure it's callable (again, if not, an error is thrown) if it is, it's called.
In the call, the identifier greet is resolved and its value passed to the function. If greet can't be resolved (i.e. it doesn't exist on the scope chain), an error is thrown. In this case, it resolves to a reference to the function assigned to greet.
When log is executed, a new execution context is created. The function declaration for log defines a formal parameter a (in its formal parameter list), so a is created as a local variable for log. The values in the call are passed to identifiers in the formal parameter list in order, so the value of greet is assigned to a. Note that initialisation and creation of a new execution context occurs every time a function is called.
The same process is followed when calling:
console.log(a);
so that within console.log, the reference to greet is passed as the first parameter, so it now references the greet function.
The behaviour of console.log is entirely implementation dependent so the internals are unknown, but for functions most tend to just call the function's toString method.
It's a handy feature of ECMAScript that an arguments object is created of the arguments passed to functions, so the values passed are always available as numeric properties of the arguments object if there is no parameter for them to be assigned to. So console.log doesn't have to define any formal parameters, it can just loop over its arguments object and process the passed values in turn.

Do I have an accurate understanding of callback functions?

I've been a Javascript tinkerer for quite some time and recently I have been trying to have a real good understanding of the code I write. I want to get really good at writing Javascript. One of the things that's confused me a little bit was the usage of callback functions. I've just avoided using callbacks up until now. Right now, I'd like to know if my understanding of how a basic callback works is accurate and also if my understanding of parameters and arguments is accurate and finally, what the purpose is of using the callback in this scenario. Is there a benefit to using the callback function I've created below? If not, when are callback functions most beneficial? I realize what I've written below is quite lengthy so for the TLDR people: Am I right in thinking It's as if I created the function "theCallback" within "myFunction"? If so, what is the benefit in the scenario below? Why not just call a function? why must the function being called be an argument in the "myFunction" function?
If the scenario below doesn't make it necessary for using a callback, when is it necessary and what are the benefits? Thanks.
Here's how I see the code below: I've created a factory function "myFunction" with two parameters "x" and "callback" and parameters are pretty much variables that will be stored with arguments when the function is called. I also created another factory function "theCallback" with two parameters "x" and "theValue". Now since these are factory functions, regardless of them being underneath a function call to "myFunction", they will be hoisted above the function call so there are no problems. Had I created a function expression with a variable, they would not be hoisted. So now my call to "myFunction" has two arguments that the parameters in it will be defined as, "3" and "theCallback". The "theCallback" argument is a function. This function has the two parameters "x" and "theValue". When "myFunction" is called, "x" is stored with the argument "3" and "callback" is stored with the function "theCallback" and then the code within "myFunction" is executed which is simply a variable declared and assigned a value of a string that contains the text "for the callback" and the callback variable (I'm viewing as a variable), which was a parameter that is now an argument which is "theCallback" function I created which also contains parameters itself, is called, and given arguments for it's code to execute. In this case, the code it will execute calls the built in alert function (or method of the window object?) and gives the alert function a string argument, followed by the
alert function called again with the argument of "x" which is stored with "3" and then again alert is called and given the argument of "theValue" which contains the string "for the callback". Now when "theCallback" function is passed as a second argument to "myFunction" and it's stored in "callback", It's as if I created the function "theCallback" within "myFunction" right? If so, what is the benefit in the scenario below? Why not just call a function, why must the function being called be an argument in the "myFunction" function?
If the scenario below doesn't make it necessary for using a callback, when is it necessary and what are the benefits?
myFunction(3, theCallback);
function myFunction(x, callback){
var value = 'for the callback';
callback(x, value);
}
function theCallback(x, theValue){
alert('this is the callback function');
alert(x);
alert(theValue);
}
Is there a benefit to using the callback function I've created below?
That's a little subjective. Using a callback is unnecessary there. Normally you would return data from one function and pass it to the other.
when are callback functions most beneficial?
When you need to deal with the data after an event has fired, instead of immediately. e.g. when a button is clicked or an HTTP response has fired.
myButton.addEventListener("click", myCallbackFunction);
I've created a factory function "myFunction"
No. That is just a function. Factory functions create class objects.
they will be hoisted
Function declarations (as opposed to function expressions) are hoisted. This isn't relevant to callbacks though. A callback is basically a function passed as an argument, it doesn't matter how it was created.
what are the benefits
The benefits are that you can have different things happen when the event fires depending on the circumstance.
Take the click event example above. Often you'll want clicking on different things to have different effects, not the one thing that addEventListener was hardcoded to make happen by the browser vendor.

what is the difference between these two

I'm very new to js so I'd appreciate some help. I have two blocks of code that I think should work identically but don't. Can someone explain how they're different? It looks like in the first piece of code, the parser enters the function directly.
function embedGameSwfAfterReg() {
embedGameSwf("{$swfLocation}", "100%", "100%", {$flashVars});
}
API.registerOnload(embedGameSwfAfterReg())
and
API.registerOnload(function() {
embedGameSwfAfterReg("{$swfLocation}", "100%", "100%", {$flashVars});
});
In the first code block, you're registering the result of the embedGameSwfAfterReg function (undefined) as the onload function (() means you're evaluating the function). Remove the parentheses to have the embedGameSwfAfterReg function itself registered:
API.registerOnload(embedGameSwfAfterReg)
This
API.registerOnload(embedGameSwfAfterReg())
runs embedGameSwfAfterReg, and then passes the return value (undefined since it doesn't return a value), to registerOnLoad
you want
API.registerOnload(embedGameSwfAfterReg)
which passes the function itself to registerOnload
Functions are objects in Javascript and can be passed directly by their names. When you add the parens, it instead runs the function and passes the result.
function embedGameSwfAfterReg() {
embedGameSwf("{$swfLocation}", "100%", "100%", {$flashVars});
}
API.registerOnload(embedGameSwfAfterReg)
and
API.registerOnload(function() {
embedGameSwfAfterReg("{$swfLocation}", "100%", "100%", {$flashVars});
});
would work the same way.
The difference is () which you have put with embedGameSwfAfterReg function in the first case
It actually calls the function there only but its different in the 2nd case.
I'm asssuming that the second example should be
API.registerOnload(function() {
embedGameSwf("{$swfLocation}", "100%", "100%", {$flashVars});
});
If so, then the difference is quite big. In the first case, the embedGameSwfAfterReg function is invoked and the embedGameSwf is called when you register. This is probably not what you want since the the return value of the function is undefined.
In the second case, the anonymous function is not invoked until later when the registerOnLoad event is raised. This is probably what you want.
API.registerOnload() takes a callback function as parameter, therefore you only have to pass in the function name as reference, otherwise the function is directly getting called when the code runs.
// Correct form is:
API.registerOnload(embedGameSWFAfterReg)
Your second sample already is an anonymous function that is handled like an function callback and therefore evaluated when API.registerOnload(callback) is calling the reference with callback() somewhere inside it's code.
Short answer:
First piece of code do nothing, because embedGameSwfAfterReg doesn't have a return statement. Probably it could even end up with an error if API.registerOnload doesn't accurately check its arguments before execution.
Second piece of code creates an anonymous-function that is passed as an argument to API.registerOnload method which (as far as I can see from method name) runs functions during an Onload event.
Long answer:
In the first piece of code you declare a new function named embedGameSwfAfterReg which resists in global-scope of your code:
function embedGameSwfAfterReg() {
// calls embedGameSwf function
}
after, you execute defined function and pass the result to registerOnload method of an object named API:
API.registerOnload(embedGameSwfAfterReg());
As you probably mentioned, declared function embedGameSwfAfterReg has no return statement, so the result of its execution will be undefined. In other words
API.registerOnload(embedGameSwfAfterReg());
is doing the same as
embedGameSwfAfterReg();
API.registerOnload();
so eventually it calls API.registerOnload() WITHOUT any arguments passed!
Second piece of code creates an anonymous function (functions are specific objects in JS, which can be passed to other functions/methods, have its own methods and executed). Then it passes created function (or better say a reference to the function) to registerOnload - method of an object called "API".
You should read topics about Objects, Function-type, scopes, anonymous functions and closures in JS. I would advise Mozilla JavaScript guide
Also feels free to play with a simplified example at jsfiddle which gives some practical hint on anonymous functions in JS.

How do I read Javascript Closure Syntax?

Based on some code in a lecture by Doug Crockford, I've created this.
var isAlphaUser = (function() {
alert("Forming Alpha User List");
let AlphaUsers = {
1234: true,
5678: true
};
return function(id){
alert("Checking Alpha Users:",id);
return AlphaUsers[id];};
}());
alert("starting");
alert(isAlphaUser(1234));
alert(isAlphaUser(5678));
alert(isAlphaUser(3456));
which gives me this:
Forming Alpha User List
starting
Checking Alpha Users: 1234
true
Checking Alpha Users: 5678
true
Checking Alpha Users: 3456
undefined
Which is quite cool, as it does the expensive setup once only, and every further call is a cheap check.
However, I can't decipher the code that does this. Specifically, I can't understand why I need the "()" at the end of the function declaration.
Can somebody explain how this syntax is working?
() calls a function. function() { } defines a function. Appending () right after immediately calls it1, and the result (also an anonymous function) is assigned to isAlphaUser.
The function() { ... }() pattern is frequently used to isolate variables to an inner scope, so those variables don't become part of the global scope.
In this case, this is what happens:
An anonymous function is run, defining a variable AlphaUsers inside that scope.
That function returns another function that takes 1 parameter. This function is a closure to which the AlphaUsers variable becomes bound (in other words, available). This function checks if the parameter passed in is contained in AlphaUsers (actually, it returns the item at that index, which is just a boolean).
The return value is assigned to a variable isAlphaUser.
Since isAlphaUser is now a function, it can be called to see if the parameter is contained in the AlphaUsers variable, but no direct access to AlphaUsers is available in the global scope (it become a sort of private variable).
1 — Note: As cwolves mentioned in the comments, beware that while () appended directly after the } works in this case, it is only because in this case the function definition is a function expression. If function is the first word on the line, the line becomes a function declaration, and that is all that line can do, the function is not anonymous (it will require a name, otherwise it's a syntax error) and cannot be called immediately inline. See Function Declarations vs. Function Expressions for more info.
The () at the end of the code is separate from the closure issue. By wrapping your function in parens and adding the () at the end you are creating an anonymous function that is run immediately with whatever arguments you pass into ().
Specifically, I can't understand why I need the "()" at the end of the
function declaration.
It creates self-invoking function, in other words, the function is executed as soon as it is parsed.
It is basically same thing when you call a function by suffixing it with () like:
myfunc(); // call this func
The top-level anonymous function returns the function that the isAlphasUser varaible refers to.
You need to call the top-level function, to get the inner-function reference.
Think of it like this, the outer anonymous function is a function factory, i.e., it returns a function.
In order to use any function (even one that returns a function) you must call it.

Categories