Closures, Private & Methods


Summary

This episode of Developer Tea delves into the concept of closures in JavaScript, explaining how they function as a mechanism for controlling variable scope and access. The host, Jonathan Cottrell, begins by defining closures using Mozilla’s official definition and illustrates the concept with nested functions, showing how inner functions retain access to the variables of their outer functions even after the outer function has executed.

The discussion draws a direct parallel between closures in functional programming and private methods in object-oriented languages like Ruby. The core idea is that both techniques serve to encapsulate functionality, restricting access to certain variables or methods to prevent unintended modifications and to create a controlled interface for interaction.

The practical benefits of using closures and private methods are explored in depth. Rather than being a security feature, this encapsulation is presented as crucial for code usability and maintainability. Examples include creating a bounded counter where the internal state can only be modified through specific exposed functions, and factoring out repeated steps into private helper methods that only make sense within a specific context.

Finally, the episode encourages developers to think more deliberately about scoping in their code. Using closures to create protective layers helps avoid reliance on global variables and implicit state, leading to smaller, more understandable functions and easier long-term maintenance. The host invites listeners to continue the conversation about closures and scoping within the developer community.


Recommendations

Communities

  • Spec Network Slack Channel — A Slack community mentioned where listeners can join to discuss topics like closures and scoping with the host and other developers from the Spec network.

Websites

  • Spec.fm — The network hosting Developer Tea and other shows like Design Details and Little Bites of Cocoa. The host encourages listeners to check it out for show notes and new features.

Topic Timeline

  • 00:00:00Introduction to closures and their relation to OOP — Jonathan Cottrell introduces the episode’s topic: closures in JavaScript. He explains that the episode will compare closures to objects in object-oriented programming, focusing on JavaScript’s implementation. He notes that many developers have encountered closures without fully understanding them, setting the stage for a deeper exploration.
  • 00:01:08Defining closures and the context of JavaScript — The host describes closures as a ‘black box’ concept that is often misunderstood. He clarifies the discussion will treat JavaScript as a language without formal classes (focusing on ES5), as it widely utilizes closures. This establishes JavaScript as a prime example for understanding closure mechanics, even as class syntax is introduced in ES6.
  • 00:02:47Mozilla’s definition and a nested function example — Jonathan presents Mozilla’s official definition of a closure: a function that remembers the environment in which it was created. He illustrates this with an example of nested functions (A, B, and C), explaining how inner functions can access variables from outer scopes. This demonstrates the core mechanism of a closure capturing its lexical environment.
  • 00:05:23Comparing closures to private methods in OOP — The host draws a direct analogy between closures and private methods in object-oriented languages like Ruby. He explains that both are ‘two sides of the same coin,’ serving to encapsulate code and control access. A closure returning an inner function is functionally similar to a class exposing only its public methods while keeping others private.
  • 00:06:23The purpose of privacy: usability and maintainability — Jonathan addresses the ‘why’ behind using closures and private methods. He clarifies it’s not about security but about creating controlled, maintainable code. By restricting access to variables and methods, developers can enforce rules (like bounds on a counter) and prevent accidental state corruption, leading to more robust and understandable systems.
  • 00:07:14Practical example: a bounded counter — A concrete example is provided: creating a counter with bounds (e.g., 0 to 10) using a closure. The internal count variable is scoped within an outer function, and only specific returned functions (like an increment method) can modify it. This ensures the count never violates the defined bounds, showcasing closure’s power for state management.
  • 00:08:45Example: private helper methods — Another use case is presented: factoring out repeated steps from public methods into private helper methods (or functions within a closure). These helpers only make sense within the context of the larger operation and shouldn’t be called independently. This promotes cleaner, more modular code by hiding implementation details.
  • 00:09:23Benefits for code maintenance and conclusion — The host summarizes the key benefits of using closures and careful scoping. They protect code from accidental errors, eliminate reliance on global variables, and lead to smaller, more focused functions. This improves long-term maintainability. Jonathan concludes by encouraging listeners to explore scoping further and join the conversation on the Spec network’s Slack channel.

Episode Info

  • Podcast: Developer Tea
  • Author: Jonathan Cutrell
  • Category: Technology Business Careers Society & Culture
  • Published: 2015-09-02T07:00:00Z
  • Duration: 00:10:49

References


Podcast Info


Transcript

[00:00:00] Hey everyone and welcome to Developer Team. My name is Jonathan Cottrell and today I’m

[00:00:05] going to be talking to you about closures. How closures can be compared to objects in

[00:00:11] object-oriented programming. Specifically, we’ll talk about it with relation to JavaScript

[00:00:16] so that most people will understand kind of how JavaScript closures work. If you’ve worked

[00:00:21] with JavaScript, you have probably encountered closures whether you know it or not. Today’s

[00:00:26] episode is brought to you by Spec. Spec is the network that I helped create with Bren

[00:00:31] and Brian and I guess we are still creating it. Spec.fm is where you can find all of the

[00:00:37] shows that are a part of Spec including design details and little bites of cocoa. Tons of

[00:00:44] really interesting content that is constantly coming out of this group of people. Spec.fm

[00:00:50] make sure you check it out. Of course, the show notes for Developer Team can be found

[00:00:54] there and there’s a player where you can play.

[00:00:56] All episodes of Developer Team and we’re constantly releasing new features on Spec.fm so make sure

[00:01:01] you go and check it out on a regular basis. Spec.fm. So closures. Closures are a kind

[00:01:08] of a black box if you haven’t studied them a little bit and I’ve done some research to

[00:01:13] prepare for this episode to talk about closures because I think they are misunderstood by

[00:01:19] a lot of programmers. Specifically, closures as they relate to languages that aren’t necessarily

[00:01:26] considered object oriented or more specifically languages that don’t have a class constructor

[00:01:34] in them necessarily. Now I’m going to go ahead and include JavaScript in this discussion because

[00:01:40] JavaScript doesn’t technically have classes yet and the question really is still up in the air

[00:01:47] about how that is going to play out. Whether or not the class structure is going to be a thin

[00:01:53] layer over the top of the prototype structure or whether or not the class structure is going to be

[00:01:56] a thin layer over the top of the prototype structure or not. So we’re going to talk about

[00:01:59] JavaScript as if it doesn’t have classes today because in ES5 it doesn’t have classes. ES6

[00:02:07] and beyond there is a class constructor for JavaScript but we don’t know entirely what

[00:02:13] that’s going to end up looking like. So for the purposes of today’s episode we are going

[00:02:17] to consider JavaScript a good example of a language that implements closures and in fact

[00:02:22] closures are used all over the place in JavaScript.

[00:02:26] Libraries that you most likely are using today. So JavaScript is a language that utilizes closures

[00:02:34] and probably will stay that way for quite a while even with class structures being introduced

[00:02:39] formally in ES6 and beyond. So let’s start with Mozilla’s official definition of closure which

[00:02:47] you can find in the show notes at either spec.fm or developer.t. The definition is closures are

[00:02:54] functions that refer to independent functions that are used to close a structure. So if you

[00:02:56] are using a function that refers to a function that is dependent or free variables. In other

[00:02:59] words the function defined in the closure remembers the environment in which it was

[00:03:03] created. So what does this mean? Well let’s say you have an outer function. We’ll call

[00:03:09] this function a and inside of function a you have function b. Now inside of function a

[00:03:16] before you define function b you have created a few variables with the var keyword. Now

[00:03:23] in JavaScript the var keyword scopes the function a and the function b. So if you have a function

[00:03:26] that does not subscribe a a bar that is dependent on the function a in function a this is a

[00:03:35] area where in JavaScript you don’t have an inner function just a part to expose a variable.

[00:03:39] Now what can be done is move an inner variable inside of function a even if a original variable

[00:03:43] does not exist and like with到 and thect

[00:03:46] you are Jobs function you can go ahead and move an inner variable inside of function

[00:03:52] a if you do and then download function b when the if the variable follows what it’s called

[00:03:56] function B. However, you do not have access to the inner function B from outside of A,

[00:04:04] and if you were to define a variable inside of function B, then you do not have access to that

[00:04:10] variable inside of function A. So this gets a little bit hairy, it gets a little bit difficult

[00:04:16] to understand, but it comes down to this simple idea that the scope of a given function is passed

[00:04:23] into other functions, so nested functions can access the variables that are defined outside

[00:04:30] of those functions. So what this allows you to do is create very interesting systems where scope

[00:04:37] is exploited in order to create the privacy of a given type of variable, or perhaps the ability to

[00:04:46] create a function returning mechanism. So for example, you can imagine that that outer function

[00:04:52] A holds a function B.

[00:04:53] inside of it, but when you call A, it returns B. Not that it returns the result of B,

[00:05:01] but quite literally it returns the function B. So calling A gives you access to the interior

[00:05:08] method of B without actually exposing B out to the world. And where this gets even more interesting

[00:05:16] is that inside of B, you can return an even further nested function C, for example.

[00:05:23] So why is this so important? Well, it’s because A is a function that returns the function B

[00:05:23] inside of B. So why does this matter? Well, if you are paying attention as an object-oriented

[00:05:28] programmer, then you’ll likely notice that this sounds a lot like private methods. In Ruby,

[00:05:34] for example, you can define private methods by simply using the keyword private, and then below

[00:05:40] that, all of the methods that you define there will be only accessible inside of that class.

[00:05:46] And in many ways, these are two sides of the same coin. If you come from a functional background,

[00:05:52] then you accomplish this.

[00:05:53] Same idea of only allowing code to be called in certain places through closures. And if you come

[00:05:59] from the object-oriented background, then you are likely to use something like private variables or

[00:06:05] private methods to accomplish the same goal. So hopefully we’ve kind of covered this idea

[00:06:11] that closures are in many ways quite similar to private methods or private variables and the idea

[00:06:18] that scope is important. But what we really haven’t talked about is why you would want to use such a

[00:06:23] thing. Why does a private method need to be created? Why not just make it all public? Why not

[00:06:30] allow all functions to be available at the top level? When I first started out programming,

[00:06:35] I thought this actually literally had to do with the security of your code,

[00:06:39] that it would be easily penetrated by some kind of hacker attack or something. But that was totally

[00:06:45] wrong, obviously. This has nothing to do with security, but it has everything to do with

[00:06:51] usability and maintainability.

[00:06:53] As a developer, even more specifically, having private methods and utilizing closures

[00:06:59] allows you as the developer to determine how things change and how they are accessed and

[00:07:07] modified by whatever other methods are used by your code. A very simple practical example would

[00:07:14] be if you had a counter in JavaScript and you set your counter, the current count, to a variable

[00:07:21] inside of a function.

[00:07:23] And perhaps you have bounds on that counter where you never want it to go below zero and you never

[00:07:29] want it to go above 10. Now with pure JavaScript, you could simply reset that variable to a given

[00:07:36] number. And of course, you can easily set a variable to something outside of the bounds that

[00:07:42] you have defined in your program. If you instead set that variable inside of the scope of a function

[00:07:48] and then return functions that can modify that variable,

[00:07:53] but only within the bounds that you have set, now you have a controlled state where that variable

[00:07:59] will never be outside of those bounds. So you could have an increment method inside of this scope

[00:08:06] that allows you to change the variable. And because of closure scope, you can only change that

[00:08:12] variable using that particular method that you’ve exposed by returning it.

[00:08:18] Another example of this is if you are creating a class that has a few methods, and each of these methods

[00:08:23] repeats the same three or four steps, you may want to factor out those three or four steps

[00:08:29] into their own private method. But that doesn’t mean those three or four steps necessarily need

[00:08:35] to be called on their own outside of the context of the class that holds the methods that should

[00:08:40] be called on their own. And this is a perfect example of when you would use private methods

[00:08:45] in your classes, is when those methods only make sense in the context of another method,

[00:08:51] particularly of another method.

[00:08:53] The same is true for JavaScript. A lot of the time, we create variables that are accessible in a scope

[00:09:01] that they shouldn’t be accessible in. So when in doubt, it makes sense to create a function scope,

[00:09:08] create that closure, and give yourself that protective layer. Not only do closures kind of protect you

[00:09:15] from yourself of overriding data or perhaps accidentally setting state in the wrong way,

[00:09:21] but they also make your code.

[00:09:23] Much easier to maintain because you aren’t relying on global variables or implicit state,

[00:09:29] and your methods are much smaller, typically. Your functions end up being smaller,

[00:09:34] much easier to tell what exactly is going on, what is being read from where,

[00:09:39] and what is being written where. I encourage you to look deeper into the idea of creating

[00:09:45] private versus publicly accessible variable scoping and function scoping or method scoping.

[00:09:52] Learning about scoping is a great way to learn about scoping.

[00:09:53] Learning about scoping is a great way to learn about scoping.

[00:09:53] Learning about scoping is a great way to learn about scoping.

[00:09:53] Scope will change the way that you see the libraries that you use. It’ll change the way

[00:09:58] that you write your own code. And if nothing else, I hope that you start a conversation

[00:10:03] about closures, about variable scoping and method scoping with the people that you work with and

[00:10:09] perhaps with people that you talk to online. Start the conversation with me. If you go to

[00:10:13] spec.fm slash slack, you can join the Slack channel for the spec network. And I’m in there.

[00:10:21] The guys from Design Details are in there.

[00:10:23] And there’s a bunch of people who are ready and willing to talk about all these kinds of subjects.

[00:10:28] Go and check it out. Spec.fm. Thank you again for listening to today’s episode of Developer Tea.

[00:10:34] If you have questions or thoughts, you can send them to me at developertea

[00:10:38] at gmail.com. There’s also a contact form on developertea.com. Until next time, enjoy your tea.