cdecde57
cdecde57

Reputation: 19

JavaScript Arrow Function question, syntax problem

First off, sorry for the vague title, I honestly don't know how to explain it without directly showing. I am new to JavaScript and have been learning arrow functions, however, I do not recognize this type of arrow function/syntax.

Currently, I am creating a website and am adding a session cookie using a passport with mongoose. The tutorial I am using has a very peculiar way of using the arrow function and am unable to find any information online pertaining to the syntax.

This is the code simplified

foo(bar)(()=>{
    ... Code Here ...
});

I understand the arrow function, but what I do not understand is how the parenthesis work in this situation and what really is going on?

        |
        V
foo(bar)(...)

I haven't been able to find anything online about this, and weird enough it runs without any errors when I run the function in the tutorial, however, if I do this with something like this,

function foo(){
    console.log("In foo");
}

foo()(()=>{
    console.log("In bar");
});

I will get an error saying

foo is not a function

The actual code being run will be down below if required

(This code is being run on a server, the req is the request data sent to a GET request, I am using passport JavaScript and mongoose here. The res variable is the response to the user, and yes this code works just fine no errors and it does what it needs to, I just don't understand how this syntax works).

req.authenticate("local")
 ((req, res)=>{
   res.redirect("/");
 });

Upvotes: -1

Views: 132

Answers (2)

Ray Chan
Ray Chan

Reputation: 1180

req.authenticate("local") is returning a function that accepts another function, you can think of it like this:

// foo can be viewed as a function because the return value from
// req.authenticate("local") is a function
const foo = req.authenticate("local");

Now, if you think of foo as a regular function, then foo(bar) should be a familiar syntax to you

The syntax works is because of the fact that req.authenticate("local") is returning a function, so that you can call it with subsequent arguments.

However, in your custom code

function foo() {
    console.log("In foo");
}

you are not returning a function, but implicitly returning undefined. As a result, the subsequent call will result in an error.

Upvotes: 1

Musa
Musa

Reputation: 97707

What you have there is a function foo being called with a parameter bar, which returns a function that is taking an arrow function as a parameter.
So the open bracket after the bar is where you are calling the function returned by foo.

function foo(bar){
    console.log(bar);
    return function(arrow){
        arrow();
    }
}
    
foo('bar')( ()=>{
    console.log("In bar");
} );

Upvotes: 2

Related Questions