This SO answer elegantly explains how a "function with multiple parentheses" like the one below works:
myFunction(3)(4)
But I'd like to google it and read more about it. Does this way of constructing a function have a name?
There is no such thing as a "function with multiple parentheses".
However, you can write a function that returns a function. So you pass arguments to your function with 1st parentheses, get a function in return, and pass arguments to the returned function with 2nd parentheses.
This is mainly used for IIFE when combined with closure. This technic is also called currying, as suggested by #CRice.
Related
So I decided to "re-learn" JavaScript since I forgot quite a bit. I stumbled across the "immediately-invoked function expression".
I understood everything except the () at the end.
Example:
!(function(){
console.log("Works");
})() // <----
I noticed that without it, it didn't run. But with it, it worked.
Why does the () matter?
The other, similar questions I found did not have the same exact question, I also searched on the web, still nothing.
The way you execute any function is by putting an argument list enclosed in () after an expression that evaluates to the function.
With normal named functions, the expression is just the name of the function. An IIFE doesn't need a name, because it's just being used this once, so it's just an anonymous function expression.
But you still execute it the same way, by putting an argument list after the expression. Usually an IIFE doesn't need any actual arguments, so the argument list is empty.
(function() {
console.log("Works!");
})();
is essentially the same as
function tempName() {
console.log("Works!");
}
tempName();
except that it doesn't create the name tempName.
And if you left out the () at the end, it would be like writing just
tempName;
which is just a reference to the function, it doesn't invoke it.
In this article js log function, there is a statement:
Function.prototype.apply.call(console.log, console, arguments);
I'm really confused by this statement.
What does it do?
How can I analyse this statement?
Or with some thoughts or tools, I can figure it out step by step?
Can it be simplified to more statements to achieve the same result? for instance: var temp = Function.prototype.call(console.log, console, arguments); Function.prototype.apply(temp);
Thanks for the response.
Apply is a function on the function prototype. Call is also a function on the function prototype. Apply is a function, therefore, it has call on it's prototype. All this is doing is calling the apply function.
Read more about apply here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
What does it do?
It calls console.log with console as this during the call, passing along the arguments in the
pseudo-array arguments as discrete arguments to the function.
So if arguments had "hi", "there" in it, it would be the same as:
console.log("hi", "there");
How can I analyse this statement?
Or with some thoughts or tools, I can figure it out step by step?
Let's start with what the apply and call functions are: They each have the ability to call a function
using a specific this during the call and passing arguments to that function. apply gets those
arguments from a single array (or anything array-like). call gets those arguments as individual arguments.
Normally, you'd see apply or call used like this:
someFunction.apply(valueForThis, ["arg1", "arg2", "arg3"]);
// or
someFunction.call(valueForThis, "arg1", "arg2", "arg3");
The only difference between apply and call is how they expect to get their arguments (apply = in
an array-like thing, call = as individual arguments).
So why, then, isn't that code doing this?
console.log.apply(console, arguments);
It's being cautious: console.log is a function provided by the host. It may not be a true JavaScript
function, and so it may not have the apply property.
So that code is avoiding relying on console.log having the apply property.
Which is where Function.prototype comes in. It's a reference to the object that is the prototype of all true JavaScript functions.
That prototype is where the apply and call properties on JavaScript functions come from.
So if we're worried that console.log doesn't have it (e.g., in case it doesn't inherit from Function.prototype), we can grab apply from that prototype object directly.
So the code is using call to call apply, and using apply to call console.log.
Can it be simplified to more statements to achieve the same result?
Not really, there's not a lot we can separate. I'll try to use variable names to clarify:
var thisValue = console;
var functionToCall = console.log;
var applyFunction = Function.prototype.apply;
applyFunction.call(functionToCall, thisValue, arguments);
Let's take this one part at a time.
Function.prototype.apply, more commonly seen as myBigFatFunction.apply, lets you call a function with a different this context than it would normally have. The difference between apply and call is that the former takes an array of arguments, the latter takes direct arguments after the first. Example:
myStr.substring(5)
String.prototype.substring.apply(myStr, [5]);
String.prototype.substring.call(myStr, 5);
^ all equivalent
However, for reasons I can't fully explain myself, some browser-native functions accessible to JavaScript don't have this function as a property (eg, console.log.apply). It's still possible to manually call it in the same manner though; so that console is still this, when it calls log, and that's what the given function is doing.
The reason for all that complication is that they want to pass in the arguments special variable. This is a keyword that exists in all functions, which represents all arguments to the function as an array-like object (so, suitable for Function.prototype.apply)
Your variable suggestion would likely simply call console.log once with console as argument one, and arguments as variable two, and return the result, rather than give you a function in a variable. If you want a shortened reference, it's possible you could use Function.prototype.bind, but that could actually lengthen your code.
I've noticed in Javascript there are 2 different ways to use functions:
Use the variable followed by a dot and then the function, like string.trim();
Use the variable inside the function, like parseInt(string)
What are the differences?
Are the one in point #1 not functions? How are they called?
I know inside parenthesis you can have more variables, but why is str.trim() and not trim(str)?
They are both functions, but I believe the first example in your question is normally called a method.
I'd encourage you to read the really useful Functions chapter of Eloquent Javascript. Just a couple of extracts that seem relevant:
A function definition is just a regular variable definition where the
value given to the variable happens to be a function.
and
A function is created by an expression that starts with the keyword
function. Functions have a set of parameters (in this case, only x)
and a body, which contains the statements that are to be executed when
the function is called. The function body must always be wrapped in
braces, even when it consists of only a single statement (as in the
previous example).
A function can have multiple parameters or no parameters at all.
I would also keep in mind that in JS almost everything is an object, or as someone else put it:
Since functions are objects, they can be used like any other value.
Functions can be stored in variables, objects, and arrays. Functions
can be passed as arguments to functions, and functions can be returned
from functions. Also, since functions are objects, functions can have
methods
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.
Trying to figure out what this means in javascript.
(function(document) { ... } )(document);
It is isn't using jQuery, so is this just a javascript way of making this wait till document is ready to execute?
Thanks.
This won't wait for the document to be ready, this will execute the content of the function immediately. Putting the function definition in parenthesis makes it an expression, which returns a value being the function, making it directly executable. This pattern is called an Immediately-Invoked Function Expression (IIFE).
This is probably used in conjunction with a minifier like the Closure Compiler.
Inside the function, document is a local variable. This makes it possible for the minifier to reduce its name to a one or two character name.
Note also that all variables defined inside the function will be local : they won't leak in the global scope, which may be interesting if this is only part of the script.
This creates an anonymous function that takes a single argument, and immediately calls it passing document as the argument.
This:
function(document) { ... }
creates a function taking one paremeter.
This:
(function(document) { ... })
makes it (the code, not the function) a valid expression. See here.
This:
(function(document) { ... } )(document);
calls that function with document as a parameter.
It's a basic modularization pattern. In different environments you could've passed some other object instead of document, but nothing inside that function has to know bout it.
This is called self-executed function. It evaluates the anonymous function taking a parameter called document with that parameter passed in.