1

My current understanding is that closures are a way for functional programming languages / languages with first class functions to create an object like entity (Some data and a way to act on that data)

Now, in Javascript, we already have built-in objects, and can simply use Object.create(somePrototype) to create an object. Functions are themselves objects in Javascript.

So why do we use closures? Why can't (React)Hooks etc be built using built-in objects?

  • When you declare a variable in a function, you can only access it in the function. These variables are said to be scoped to the function. If you define any inner function within another function, this inner function is called a closure. It retains access to the variables created in the outer function. – vanowm Jan 08 '23 at 21:28
  • React hooks are not functional. The very reason they exist is to enable devs to opt out from FP when using functional components. Conversely, you can have a textbook example of a functional React app with class components if they are stateless and you centralise state management with redux. What defines FP or OO are not the artefacts used to implement them in a given language. You can implement algebraic data types, which are an FP abstraction, with classes (see the fantasyland spec) or functions (the staticland spec) in JS. It doesn't matter. – geoffrey Jan 09 '23 at 19:19
  • @geoffrey understood. you can always implement it using objects closures etc. but my question was why closures when objects exist? from what I've read, closures help you achieve a lot of the things that an instance of a class would achieve in languages like Java i.e asbtraction, encapsulation, private fields etc. but when we already have built in objects, then why closures? – Kishan Kumar Jan 10 '23 at 22:30
  • At the top of my head, things involving closures which don’t look like objects are memoization, currying, throttling... How contrived would it be to implement them with objects. I could also ask why have objects when you can have type classes and first class functions. Multiple inheritance in OO languages is a pain and Java 8 included lambdas for a reason. Closures were also the only way to implement modules and private fields before ES6 if your question is more historical, but the truth is JS is multi-paradigms and therefore supports multiple ways of doing comparable things. Nothing strange. – geoffrey Jan 11 '23 at 10:23

0 Answers0