0

I'm finally getting back into serious software development after a year off and lost my javascript reference book. Sorry if this is a stupid question, but I've forgotten what this ending parenthetical means in javascript.

Here is some example code:

login: function (req, res) {
    example.function('optionA', function (err, user) {
        if (err) return res.send(err);
        return res.send(user);
    })(req, res);
});

It's that (req, res) that is confusing me, how exactly does that work?

Thanks in advance. Not feeling like Albert Einstein right now!

Zach Cook
  • 604
  • 12
  • 33
  • 1
    That's an "Invocation Operator" which invokes the function! – Ram Aug 26 '17 at 21:10
  • 1
    @Acemad it looks like the function was already defined - does it still qualify as an IIFE? – Frank Modica Aug 26 '17 at 21:47
  • @FrankModica My bad, you're right, it's not an IIFE, got a little confused. `(req, res)` are arguments for the function returned by `example.function`, also there's an extra parenthesis at the end of the snippet. – Acemad Aug 26 '17 at 22:30

2 Answers2

5

It looks like example.function returns a function, which you are then invoking and passing in req and res.

It's like doing this:

let func = example.function('optionA', function (err, user) {
    if (err) return res.send(err);
    return res.send(user);
});

func(req, res);
Frank Modica
  • 10,238
  • 3
  • 23
  • 39
1

This is an example of an Immediately-invoked function expression. You're creating a function and invoking it immediately. More details: https://en.wikipedia.org/wiki/Immediately-invoked_function_expression