Skip to content Skip to sidebar Skip to footer

Why Return Anonymous Function From A Javascript Function

Here the function returns an anonymous function: function respondWithResult(res, statusCode) { statusCode = statusCode || 200; return function(entity) { if(entity) {

Solution 1:

Why is it that we are returning an anonymous function here that returns a value? What advantages do we have and when to try something like this?

This is generally done because it has access to the scope of the function it was declared within. i.e. the local variables statusCode and res. Without more context it isn't immediately obvious why that is useful here.

How and what is this anonymous function's argument entity is populated with?

It's a function argument. It gets populated with whatever gets passed to it when it is called (which isn't in the code you shared).

As you pointed out, the function is returned (not immediately executed). Some other code will call it later.

Now, res is what we pass to respondWithResult. Is that what the anonymous functions gets in the argument? If

No. The returned function is passed to then. When the promise resolves, the result is passed to it.

Post a Comment for "Why Return Anonymous Function From A Javascript Function"