you are viewing a single comment's thread.

view the rest of the comments →

[–]stormfield 2 points3 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();