Confused by the nested functions in javavascript

I see these nested functions all the time in js and was wondering if someone could explain what exactly is happening in them. Here’s an example of what I mean.

  dns.lookup(longUrl.hostname, (err, address, family) => {
    if (err) {
      return callback(err, null);
    }
    return callback(null, longUrl.origin);
  }); 

What’s happening here? Is the everything in the function just all part of the arguments?

The first thing to grasp is that functions can be passed as arguments to functions and can be returned from functions. If you already know that then cool.

The next part is deciphering the syntactic sugar going in the code above.

a function in js is defined as follows…

function foo(args) {
  ...code...
}

or

const foo = function(args) {
  ...code...
}

in the second example we are assigning the function to the const variable foo and can be written in several different ways.

const foo = (args) => {
  ...code..
}

in this style we have removed the function language and added an arrow operator => after the (). this is identical to the function definition above it. it is just an ‘easier’ method (having to write function out constantly can be a pain and muddy up the code)

note that functions don’t always require names in JS (skip if you already know this).

in the example you provided one of the parameters of the function dns.lookup is the result of a function which will return either the result of function callback(err, null) or callback(null, longUrl.origin) depending on whether err is true or false.

so instead of building this function somewhere else and then calling here, it is defined on the spot (maybe you don’t need to use this function anywhere else).

although looking at the code i’m not sure what the purpose of passing address and family are as they are not being used.

1 Like

I found this example of someone using the same function https://www.youtube.com/watch?v=zR5JXoR_xeo and the function isn’t used as an argument. It looks like it’s called after the other function is called but with args from the other functions output.