Introduction
The most infamous interview question for JavaScript has got to be explaining closures. Because of this it may seem that closures are a complex topic, but in reality the idea of closures is actually pretty simple. All you need to know about closures is they they are a mechanism in JavaScript for handling variable scope. In this video I explain in depth exactly what closures are, how to use them, and why they are important.
🧠 Concepts Covered:
- What closures are
- How closures work in JavaScript
- Why closures are important
- When to use closures
🌎 Find Me Here:
My Blog: blog.webdevsimplified.com
My Courses: courses.webdevsimplified.com
Patreon: www.patreon.com/WebDevSimplified
Twitter: twitter.com/DevSimplified
Discord: discord.gg/7StTjnR
GitHub: github.com/WebDevSimplified
CodePen: codepen.io/WebDevSimplified
#Closures #WDS #JavaScript
Video
Hello, everyone in today's video, I'm gonna be explaining to you exactly what closures are and you'll be surprised how simple they are to understand.
Once you wrap your head around the idea so let's get started now.
Welcome back to web, dev simplified.
My name is Kyle.
And my job is to simplify the web for you.
So if that sounds interesting make sure you subscribe to the channel for more videos, just like this one.
And now to get started I, just have really simple JavaScript on the left side here, and then the output showing up on the right-hand side.
And this is very simple code.
We have a variable called my name, a function called print name, which prints out our name whenever we call it and then we're calling that function.
And as you can see we're getting Kyle printed out over here on the side.
And what you probably don't realize is this is using closures.
This entire thing is one giant closure and that's because most of the time when you run code in other languages, for example, you cannot access variables outside of a function inside of that function.
That is just not always possible in other languages, but it is possible in JavaScript, and it is what we call a closure.
So this variable that is external to this function is actually available internally inside this function.
This is a global variable, essentially and it's available inside this function.
And the way closures work in JavaScript is that every scope.
So for example, we have the entire JavaScript file that is one scope.
And then our function is another scope.
So every scope has access to everything outside of its scope.
So our function has an outer scope of our entire file.
So it has access to everything inside the outer file.
And one thing that's really interesting.
If we change this here to a variable that can be renamed, so we have our name as Kyle up here.
And we change our name down here, we'll just say that the new name is going to be Joey, and we save that you can see this now prints out Joey and so it's, not just taking the name that is defined when the function is defined it's, actually taking the current live value of that name.
It goes, for example, if we have the name here, and then we come down here change - something else will change it decayed.
And then we print out the name one more time you can see that it says, Joey and then Kate it's constantly going with whatever the most recent value of that variable is.
And now this right here is not the most useful way that you can use closures.
I mean, it obviously is a way you can use them.
But when most people think of closers, they think of functions inside of other functions.
So let me jump to another example.
Now.
So here is the more common use case of closures where most people talk about closures.
And as you can see, we have a function here called outer function.
And that function is returning another function inside of it called inner function.
And as you can see down here, we're calling outer function with the variable outside.
So now we are getting a new function.
And then lastly we're calling that new function with the variable inside so what's happening is that when we first call this outer function, we have this.
Outer variable which we set to outside, which gets set.
And then we have this function that gets returned here.
And the reason we're able to access this, outer variable inside of this function is because of closures.
And now it's kind of weird when you think about it at first because this outer function runs and this, outer variable is only available inside this function.
But this function is done executing.
For example, if we just remove this code here, you can see nothing prints out and that's, because we call this outer function right here.
And it executes all of the code and then it's done executing.
And this outer variable is no longer accessible.
For example, I can't, log out the outer variable.
If I try to it's, just gonna give me an error as you can see, it doesn't actually exist.
So how is the inner function able to access this? Outer variable, even after it's done being executed, because the outer variable has gone out of scope, and that is where closures come in.
So what happens is this inner function is essentially saying, okay, I'm inside this outer function.
It has this.
Outer variable so I'm going to save this, outer variable I'm going to make sure I know what this outer variable is at all times.
And even if the function that defined this variable is no longer I'm executed anymore.
It exits out of the function, it's.
Okay, I'm still going to keep track of the outer variable and that's.
Why you can see outer is being printed out outside here.
And we had in a variable also being printed out if I for example, passing an inner variable.
You can see it gets printed out right there.
And the most common use case for this.
A lot of times is to have variables that you pass into functions that can be accessed inside of other functions.
We can also create a variable inside of here, we're going to call this outer two and we're going to set this equal to high.
And we can also log that inside of here.
So we can say console dot log I would over to.
And you can see high is being printed out again.
This is inside the scope that is outside this function.
So this function is contained inside this function.
So everything in the outer function is available inside the inner function since in JavaScript anything on the inside has access to the things on the outside of its scope.
Essentially it has access to its parent, scope its parents, parent, scope.
And so on.
Everything that is outside of it.
And it has access of course to the things inside of it.
Now this here is a fairly contrived example.
So probably one of the more common use cases where you're going to see this is if you're using something like Axios or fetch.
So if we come in here, and we have a function that's going to do fetch.
So we want to fetch, you know, for example, some URL so we're gonna just say, you know, URL, whatever it is some random URL that you're fetching.
And then inside of here, you're going to have an actual promise that's being returned.
So we can say dot been, and this is going to take a function.
And this function is a function that's inside our outer function.
And inside of here, we would have access to our outer variable.
So we could say outer variable, for example, and in most cases, we'd probably pass in the URL here, and we pass it in here.
And again, we'd have access to that URL inside this inner function.
And now obviously this looks a bit different.
This is an arrow function, not a standard function, but either way it's still a function defined inside of another function.
And this inner function has access to all of the scope of this outer function.
So it has access to this URL variable, even though this fetch is only going to call this dot vend function long after outer function is done being called really all.
You need to know about closures is that when you have a function defined inside of another function, like this that inner function has access to the variables and scope of the outer function E.
If the outer function finishes executing, and those variables are no longer accessible outside that function.
So if you enjoyed that video make sure to check out my other videos, linked over here and subscribe to the channel for more videos, just like this one.
Thank you very much for watching and have a good day.
FAQs
What are the few common uses for closures? ›
Closures are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.
What is closure explained? ›A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
What is the difference between scope and closure? ›The lexical scope allows a function scope to access statically the variables from the outer scopes. Finally, a closure is a function that captures variables from its lexical scope. In simple words, the closure remembers the variables from the place where it is defined, no matter where it is executed.
How would you use a closure to create a private counter? ›3How would you use a closure to create a private counter? You can create a function within an outer function (a closure) that allows you to update a private variable but the variable wouldn't be accessible from outside the function without the use of a helper function.
What are the two types of closures? ›There are two major categories of packaging closures. These are dispensing closures and non-dispensing closures.
How many types of closures are there? ›There are two kinds of closures: An escaping closure is a closure that's called after the function it was passed to returns. In other words, it outlives the function it was passed to. A non-escaping closure is a closure that's called within the function it was passed into, i.e. before it returns.
What is the rule of closure? ›The principle of closure states that when we look at a complex arrangement of visual elements, we tend to look for a single, recognizable pattern. In other words, when you see an image that has missing parts, your brain will fill in the blanks and make a complete image so you can still recognize the pattern.
What is the psychology behind closure? ›Closure or need for closure (NFC), used interchangeably with need for cognitive closure (NFCC), are social psychological terms that describe an individual's desire for a clear, firm answer or peaceful resolution to a question or problem to avert ambiguity.
What is an example of closure? ›Another example of closure is a funeral. A funeral is for those that have passed and offers a sense of closure for the loved ones of the departed.
Are closures used for currying? ›Curried functions are also an important application of closure. They split a function with many parameters into functions with only one parameter each. The context between function calls is saved thanks to closures (outer-inner pattern).
How are closures different from functions? ›
Difference between Function and Closure
Function is declared using func keyword whereas Closure doesn't have func keyword. Function has always name but Closure doesn't have. Function doesn't have in keyword but closure has in the keyword.
In simple terms, the scope is agreed with the client, key stakeholders and signed off by the sponsor or project board. Everyone agrees that the scope is frozen and cannot be changes unless… Yes, the scope can be changed but only through a formal scope challenge meeting.
What could be the alternative to closure? ›- Babel.
- FusionReactor APM.
- ReSharper.
- Semmle.
- SonarQube.
- Coverity.
- CodeScan.
- JProfiler.
Closure is something people seek at the finality of something. For example, people seek closure after a romantic relationship ends; however, this is not the only kind of closure that people desire. For instance, after a parent dies, their children might need some form of closure to deal with their grief.
How do you implement closures? ›Closures are typically implemented with a special data structure that contains a pointer to the function code, plus a representation of the function's lexical environment (i.e., the set of available variables) at the time when the closure was created.
What are the disadvantages of using closures? ›- The variables declared inside a closure are not garbage collected.
- Too many closures can slow down your application. This is actually caused by duplication of code in the memory.
Lace closures are easier to handle and the installation takes less time. These are the most commonly used closures and the knots of hair can be bleached to make it look more natural.
What type of closure should I get? ›Closures may be sold from 8 inches to 22 inches long, while some are bought with bundles. The closure length you might want depends on how you want it to look once you wear it. Mostly, if you have a bundle of 12 inches, 14 inches, and 16 inches bundles, go for the shortest inches for closure, which is 12 inches.
What is a 4 closure? ›Fourth Closing means the closing of the purchase and sale of the Securities pursuant to Section 2.1(c).
What is a roll on closure? ›(RO) Aluminium or lacquered tinplate cap for sealing on to narrow-necked bottles with a threaded neck. The unthreaded cap is moulded on to the neck of the bottle and forms an airtight seal. From: roll-on closure in A Dictionary of Food and Nutrition »
What is a 5 5 closure? ›
A 5x5 lace closure is a specific size of lace closure. The "5x5" refers to the size of the lace, which is 5 inches by 5 inches. This size is considered a medium size and is often used for hairstyles that require a medium-sized closure to create a natural-looking hairline.
What is the law of closure simple? ›The Law of Closure
When there is missing information in an image, the eye ignores the missing information and fills in the gaps with lines, color or patterns from the surrounding area to complete the image.
Closure is important after a breakup because:
Your brain needs an authentic narrative to make sense of what happened. Without closure you might keep going back to a relationship that wasn't working. You could be doomed to repeat the same relationship patterns the next time around without closure.
Forgiveness is different than closure. As Oprah said, forgiveness is giving up hope that the past could be any different. Closure is the psychological version of closing something, "moving on." You can forgive but still not have closure. Some things are not meant to "move on" from.
Why do I struggle with closure? ›The need to avoid closure is often thought to be born of a person's desire to avoid commitment or confrontation. In other words, someone avoiding closure may not want certain questions answered. They might be afraid of what they'll learn.
Why do narcissists hate closure? ›Narcissists are unable to handle uncomfortable feelings after a relationship ends. Instead, they discard you and will not think about you at all. They do not want to experience pain, which is also why they won't offer closure after a breakup.
Why is getting closure difficult? ›Research indicates that certain types of personalities are different in the ways they approach closure. One study found that people who prefer order and predictability – having a more rigid way of thinking and a low tolerance for ambiguity – struggle when they are unable to find the answers to help them move on.
How do you get closure from trauma? ›- Take full responsibility for yourself. It's ultimately up to you to take the necessary actions to help move you forward. ...
- Grieve the loss. Take plenty of time to do this. ...
- Gather your strengths. Focus on the positives. ...
- Make a plan for the immediate future. ...
- Create a ritual.
- Honor your feelings, and grieve the relationship you lost. ...
- Forgive yourself. ...
- Forgive your ex. ...
- Block your ex on social media. ...
- Lean on your tribe for emotional support. ...
- Practice self-care routinely.
- Understand that closure begins with yourself. ...
- Accept that closure requires patience. ...
- Let yourself absorb the emotions. ...
- Effectively communicate one last time. ...
- Don't blame yourself. ...
- Try being a forgiving person. ...
- Hope for the best for your ex. ...
- Think of a closure ceremony.
What are the benefits of closures? ›
- Encapsulation: Closures allow you to create private variables and functions that can only be accessed from within the closure. ...
- State retention: Closures allow you to retain the state of a function even after it has finished running.
Some common types of closures include continuous thread closures (CT), disc top caps, child resistant (CRC) closures, pumps, and sprayers.
What is the difference between currying and closure? ›Currying means that the closure does not have to receive all of its arguments at once, but separately. I've found this useful metaphor around the internet: Think of currying as adding ingredients (arguments, or other spices) to a function one by one.
What problem do closures solve? ›Closures are useful because they let you 'remember' data and then let you operate on that data through returned functions. This allows javascript to emulate private methods that are found in other programming languages. Private methods are useful for restricting access to code as well as managing your global namespace.
Are closures like lambdas? ›Lambda functions may be implemented as closures, but they are not closures themselves. This really depends on the context in which you use your application and the environment. When you are creating a lambda function that uses non-local variables, it must be implemented as a closure.
What is the difference between lambdas and closures? ›A lambda expression is an anonymous function and can be defined as a parameter. The Closures are like code fragments or code blocks that can be used without being a method or a class. It means that Closures can access variables not defined in its parameter list and also assign it to a variable.
Can you over tighten a scope? ›Always tighten base and ring screws to the manufacturer's specs. Overtightening can damage the scope body and affect performance.
Should you Loctite your scope? ›For example, we do not recommend the use of Loctite or other similar products in mounting our optics. These products can act as a lubricant, creating additional torque on the screws, which can exceed the recommend specs and actually damage your riflescope, limiting your ability to dial shots.
Why are old scopes so long? ›The thinner the lenses can be made, the more closely they can be placed together. This also applies to housing and moving the lenses to change magnifications as well. Having them farther apart allowed for more “error” correction.
Can you name two common uses for closures? ›Here are some advantages of closures: They allow you to attach variables to an execution context. Variables in closures can help you maintain a state that you can use later. They provide data encapsulation.
What are closures used for react? ›
In simple closure is a function that has access to variables in its parent scope, even after the parent function has finished executing. That's the simple straightforward definition. We can use the ability of closures inside react to make things easier.
What are closures used for in Python? ›Closure in Python can be defined when a nested function references a value in its enclosing scope. Closures provide some form of data hiding. A closure can also be a highly efficient way to preserve state across a series of function calls.
Can you reuse the same closure? ›Can you reuse a closure? With proper care, you can reuse a closure over and over again for different hair looks and styles. This is one of many things that makes closures so great!
What is emotional closure? ›Closure is any interaction, information, or practice that allows a person to feel that a traumatic, upsetting, or confusing life event has been resolved.
Are closures used in functional programming? ›Closures are one of the most powerful and elegant features of functional programming, but they can also cause memory leaks and performance issues if not used carefully. In this article, you will learn what closures are, how they work, and how to avoid common pitfalls when using them in your code.
Why is React good for front end? ›Compared to other frontend frameworks, the React code is easier to maintain and is flexible due to its modular structure. This flexibility, in turn, saves a huge amount of time and cost to businesses.
What programming languages use closures? ›Closures were fully adopted and implemented in a programming language called PAL in order to support functions which were also lexically scoped (similar to JavaScript). Closures are typically used in places where there is a need to return functions from higher order functions.
Is a closure always a function True False? ›Explanation: In JavaScript, closures are created every time a function is created, at function creation time. Technically, all JavaScript functions are closures: they are objects, and they have a scope chain associated with them.
What is closure used for JavaScript? ›What is closure in JavaScript? Closure in JavaScript is a form of lexical scoping used to preserve variables from the outer scope of a function in the inner scope of a function. Lexical scoping is the process used to define the scope of a variable by its position in the source code.
What is one of the purposes of closure? ›Closure allows students to summarize main ideas, evaluate class processes, answer questions posed at the beginning of the lesson, and link to both the past and the future.
What is the significance of closure? ›
Closure is achieved when we are satisfied that the puzzle has been assembled to our satisfaction, that the answers have been reached and it is therefore possible to move on. When people most need closure it is usually because the termination of the event is significant to them, holding particular value and meaning.