As a frontend developer with around 6 years of experience focusing on React, Next.js, and similar technologies, I have a solid grasp of JavaScript's advanced features like closures, prototypal inheritance, and iterators/generators. While I know these concepts are crucial, especially in libraries I use, I seldom engage with them directly in my code. I'm looking for insights from fellow developers on how they practically apply these features in their work.
1. For closures, besides their use in hooks and callbacks, in what specific scenarios do you create closures for tangible benefits?
2. Regarding prototypal inheritance or classes, are there situations beyond typical class definitions where you utilize deeper inheritance or advanced class features? What problems do these patterns solve?
3. Do you often create custom iterators or use generator functions in your projects? What tasks make these features valuable?
I'm eager to hear about concrete examples where you consciously opted for these tools rather than depending on defaults from frameworks.
4 Answers
I rely on closures frequently, especially for dependency injection and when working with frameworks. For example, they help in managing state in routing. I even wrote a blog about my approach to using them for dependency injection, which has been quite effective for me.
This syntax in trpc docs just went over my head. I may need to dive deeper into it.
I implemented an iterator protocol once in a custom map class to mimic its built-in behavior. I find iterators great for using objects in loops, but they aren't something I use daily. Generators are useful in projects where I want to yield values without constructing an array first, but they are somewhat niche.
I believe there's a bit too much emphasis on closures. They're not very complex if your code is well-organized. As for inheritance, it’s pretty much fallen out of favor; I usually stick to basic class structures and avoid deep inheritance because it complicates understanding.
React's use of hooks can cause a bit of a mess with closures since it means you have to manage state carefully in a series of function calls. That said, I use closures when it makes sense, often in factory functions, since they can offer unique benefits over classes.
Your blog on Dependency Injection is insightful.