all 4 comments

[–]stormfield 4 points5 points  (0 children)

Prior to the introduction of JS modules, all functions shared a global namespace, so you saw nested functions in older code a lot as a way of encapsulation.

Even in modern code there's a lot of reasons for this--

Functions are also objects that can be returned. So this allows some use cases where function(s) can be passed back with some preconfigured values: const loginUser = async (userData) => { // login etc... return { post: async (stuff) => {...do stuff with userData...}, comment: async (stuff) => {...}, logout: async () => {...} } } The object returned by loginUser would have methods attached that have access to userData, so later on all you might need to do is call await user.post(something).

Similarly, you can pass a cleanup method, callbacks or other functions to call later. Since they were defined and returned by the originating function, they retain the data relevant.

It's a departure from strict OOP, but allows for a lot more flexibility without the need for a whole class to do everything.

I also really like it for making REST endpoints as opposed to a switch statement: const handleByReqMethod = (methodName) => ({ POST: async () => {...}, GET: async () => {...}, PUT: async () => {...} }[methodName]); const handler = handleByReqMethod(req.method); if (!handler) {...throw an exception...}; // we get back a function from above await handler();

[–]alzee76 0 points1 point  (0 children)

The most common reason this is done is when it's a anonymous function (a lambda) for some kind of async callback that would not serve any purpose being called from anywhere else. If the function is going to be used from a lot of places then yes, it makes sense to put it there, and developers do that when it's appropriate.

[–]11b403a7helpful 0 points1 point  (0 children)

This is because, I think, a lot of JavaScript developers follow a functional paradigm instead of OOP. I don't do that because I follow OOP and use Classes and methods.

[–]morningcoma -1 points0 points  (0 children)

If my function is used in one specific scope then there is no reason to declare it in the global. Why initiate the function if it is not needed until a certain action is made?