Skip to main content

What is a Factory Function?

I hadn’t heard of the factory function technique until I read What is a Factory Function? by Kyle Shevlin:

A factory function is a function that returns a new object. The key feature of a factory is that its only job is to pump out those items, just like an actual factory.

The place I use factories most often is when I want to return an object with methods but use closures to create private methods and values. Even better, I never have to even think about the this keyword.

In other words, you can write them instead of classes!

I found a good use case for this technique today while adding extra properties and helper methods to blocks I’d fetched from the Notion API, so I wanted to give Kyle a shout-out for the timely assist.

Check out Kyle’s blog for lots of other interesting coding tips.