If I call the following function
console.log("Hello World!");
I expect it to print Hello World!
and thats all fine and dandy, but what happens when I add a local function, like
console.log(target, function(err, reply) {
console.log("Hello World!")
});
It seems I can add on this local function to anything
foo(function(err, reply) {
}
I am curious
- How the local function operates inside of the other function
- Is there a certain way the local function should be handled
- Cases where this should be or shouldn’t be used.
2
Answers
Functions, in JavaScript, are first class objects. Anything you can do with an object, you can do with a function, including passing it as an argument.
The same way it "operates" anywhere else for whatever value of "operate" you care to define. e.g. If you pass it to
console.log
then it will get logged, it won’t be called because the internal logic ofconsole.log
doesn’t call functions that are passed as arguments to it. (Unlike, for exampleArray.prototype.sort()
.)Not in the general case.
That’s too broad and too much of a matter of opinion to be answered.
console.log
can accept any number of parameters and will just output all of them to the console.Passing a function to
console.log
will just output the function itself into the console.Also, in the snippet you showed,
target
is undefined and running it will throw an error.