Closures
I want to review a pattern that's really popular among computer programmers called closures.
Closures
- Use scope
- Lexical scope
- Function inside
Closures uses certain aspects of how scope works in javascript. Scope refers to the area withing a computer program where a variable is available.
JavaScript, specially when talking about functions use something called lexical scope. With lexical scope, an inner function will have access to variables in the parent function.
A closure is created when you use the function keyword inside and another function. Now that means that variables can remember the environment that they were created in. That doesn't happen in other types of languages. And it allows you to do some special things in JavaScript.
Sample Closure
function counter() {
let number = 1
return function() { console.log(number++) }
}
let steps = counter();
steps() // 1
steps() // 2
We saw this already when we talked about how the return statement works.
This function has an internal function that remembers the value of a variable.
Closure Objects
function myObject () {
let myValue = 1;
return {
display: () => console.log(myValue),
increment: () => myValue++
}
}
I'm going to show you another way that you can write something like this to make it more flexible.
You can create a function that returns an object. This is a really cool notation that works well with arrow functions to make things a lot shorter.
This function has an initialized value and two methods. It takes advantage of the ability to use functions to generate objects.
Let's take a look at how this works.
let mything = myObject();
mything.display();
mything.increment();
mything.display();
let other = myObject();
other.display();
other.increment();
One more thing. Notice that in my slides, I have an option to get more information. Closures are one of those things that seem conceptualy straightforward, but unlike other things it's hard to think of a practical example.
Thankfully, I thought about this really hard and have a video that will help. It's part of my course on Web Developer Interview code. Indeed it's one of those things that often gets asked in interviews, so check it out.