JavaScript Closures and the Lodash _.once method

Brittany Hartmire
Code Journal
Published in
3 min readJun 1, 2019

In this post I’ll provide an introduction to JavaScript closures and demonstrate how closures are applied in the Lodash library’s _.once method.

“The ability to treat functions as values, combined with the fact that local bindings are re-created every time a function is called, brings up an interesting question. What happens to local bindings when the function call that created them is no longer active?” –Eloquent Javascript, Chapter 3: Functions

In fact, specific instances of a local binding in an enclosing scope can still be referenced in the future even after the said function call is no longer active. If this sounds like a bunch of mumbo jumbo, looking at real examples is a lot easier to understand:

This means that addTwo = num2 => num2 + num1

But since the value 2 was passed in when we invoked addMe() and we assigned the returned function to the variable add2, the value of num1 is still bound to the enclosing scope.

So essentially, addTwo = num2 => num2 + 2

Since we can’t actually see the value of num1 (even though we obviously know what it is), it is called a private variable.

Eloquent JavaScript is indeed eloquent, so I’m going to quote Marijn Haverbeke again: “This feature — being able to reference a specific instance of a local binding in an enclosing scope — is called closure [ . . .] A function that references bindings from local scopes around it is called a closure.”

We can create as many closures using #addMe as we want. And we’ll see that addTwo will still work the same as before.

Now that we’ve covered basic JavaScript closures, let’s move on to _.once. The Lodash _.once method allows you to limit a function to only be invoked once. Repeat calls will return the value of the first invocation. It is a creative use of closures!

I built out my own simple version of this function.

Invoking _.once will return an inner function with the passed-in func parameter bound to it. We can invoke this inner function in the future by assigning it to a variable when we initially invoke _.once. The first time the inner function is invoked, func will have a truthy value and pass the conditional statement. Then func will be invoked using #apply and the return value will be saved inside a result variable. Func will then be reassigned to null. For all future invocations, func will be falsy and return this result from before.

Let’s see an example:

So even though we called #increment three times, the function we passed in to _.once was only invoked once.

--

--