skip to Main Content

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

  1. How the local function operates inside of the other function
  2. Is there a certain way the local function should be handled
  3. Cases where this should be or shouldn’t be used.

2

Answers


  1. 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.

    How the local function operates inside of the other function

    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 of console.log doesn’t call functions that are passed as arguments to it. (Unlike, for example Array.prototype.sort().)

    Is there a certain way the local function should be handled

    Not in the general case.

    Cases where this should be or shouldn’t be used.

    That’s too broad and too much of a matter of opinion to be answered.

    Login or Signup to reply.
  2. console.log can accept any number of parameters and will just output all of them to the console.

    console.log("hello world!", 69420, true, false, function () {console.log("hello world!");})

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search