Factory Functions vs Closures - It's a Tricky Comparison

Very often you’ll see examples of factory functions combined with closures, which for me at least made it much more difficult to properly understand what the difference is between them. You might think factory functions aren’t much use without involving closures, but that simply isn't true. A factory function is nothing more than a function that returns an object, and therefore is useful in a variety of different ways, even without closures.

Understanding how a closure can add functionality to a factory function can be tricky. For example, a factory can return one of its local variables (let’s say a string primitive) within the object that it returns. That variable can then be updated via the returned object…

Notice how I didn’t say “No problem”, and that’s because there is a problem – in JavaScript, all things other than primitives are objects, and only objects are returned by reference – therefore the string primitive in this example is returned by value, which means it becomes a new copy of the original string primitive.

The Factory vs Closure Conclusion

So, we’re not actually updating the string primitive that’s declared inside the factory, and even if the variable was of type object and therefore returned by reference... that still isn't updating it via the factory's own methods, like we can do with object oriented programming (OOP) languages…

I tell a lie… because thanks to closures, a factory’s local variables don’t expire like you might expect after the factory has finished executing. Instead, its local variables remain intact, and are accessible by the factory’s own methods which themselves can be returned by the factory as part of the object – and just like that, we have some very nice OOP!