Learn Closures In 7 Minutes

Web Dev Simplified
3 Dec 201906:55

Summary

TLDRIn this video, Kyle from Web Dev Simplified explains the concept of closures in JavaScript. He begins with a simple example, demonstrating how variables outside a function can be accessed within it, forming a closure. Kyle illustrates this with an example where a function accesses a global variable, showing how the variable's value updates dynamically. He then delves into more common use cases, such as functions within functions and how closures retain access to variables even after the outer function has executed. The video concludes with practical applications of closures using fetch and promises in JavaScript.

Takeaways

  • 😀 Closures in JavaScript allow functions to access variables from their outer scope even after the outer function has finished executing.
  • 🎯 The video introduces closures with a simple example involving a 'printName' function and a global variable 'myName'.
  • 🌟 The script demonstrates that closures are not just about accessing the value at the time of function creation, but the current live value of the variable.
  • 🔄 It shows that changing the value of a variable after a function has been defined can still affect the output when the function is called later.
  • 📚 The video explains that every scope in JavaScript, including the entire file and any functions within it, has access to the outer scope.
  • 🏢 The concept of closures is further illustrated with an 'outer function' returning an 'inner function', highlighting how the inner function retains access to the outer variable.
  • 🔑 The script clarifies that even when the outer function's execution is complete, the inner function maintains access to its variables due to closures.
  • 🛠️ Common use cases of closures are shown, such as using functions within functions to maintain access to scoped variables, which is useful in asynchronous operations like fetching data.
  • 🌐 An example with 'fetch' is given to explain how closures can be used to access variables defined in an outer function within a callback function of a promise.
  • 👨‍🏫 The video aims to simplify the concept of closures and encourage viewers to explore more through subscribing to the channel for related content.
  • 📈 The presenter emphasizes the practical applications of closures, particularly in scenarios involving asynchronous operations and callbacks.

Q & A

  • What is the main topic of the video?

    -The main topic of the video is explaining the concept of closures in JavaScript.

  • What is the presenter's name and the purpose of his channel?

    -The presenter's name is Kyle, and the purpose of his channel is to simplify web development concepts for the audience.

  • Why is the simple JavaScript code with the variable 'myName' and the 'printName' function considered a closure?

    -The simple JavaScript code is considered a closure because the 'printName' function has access to the 'myName' variable, which is in an outer scope, demonstrating the ability to access external variables within a function.

  • How does the video demonstrate that closures update with the current live value of a variable?

    -The video demonstrates this by changing the value of 'myName' from 'Kyle' to 'Joey' and showing that the 'printName' function prints the updated value, indicating that closures capture the current state of the variable at the time of function execution.

  • What is the difference between a global variable and a variable in a closure?

    -A global variable is accessible throughout the entire script, while a variable in a closure is accessible only within the function that creates the closure, even after the outer function has finished executing.

  • Can you give an example of a more common use case of closures mentioned in the video?

    -A more common use case of closures mentioned in the video is when a function (outer function) returns another function (inner function), and the inner function has access to the outer function's variables.

  • How does the video explain the scope concept in relation to closures?

    -The video explains that in JavaScript, every scope, such as the entire file or a function, has access to everything in its outer scope. This is how closures work, allowing functions to access variables from their parent scopes.

  • What happens to the outer variable after the outer function has finished executing in the context of closures?

    -In the context of closures, even after the outer function has finished executing, the inner function retains access to the outer variable because it 'remembers' the outer variable's value at the time of its creation.

  • Why are closures particularly useful in asynchronous operations like fetching data with Axios or fetch?

    -Closures are particularly useful in asynchronous operations because they allow the inner function, which is called after the outer function has completed, to still have access to the outer function's scope, including variables that are needed to process the data once the promise resolves.

  • Can you provide an example of how closures are used with asynchronous functions like fetch?

    -The video provides an example where an outer function is defined to fetch a URL, and the fetch function's '.then()' method contains an inner function that has access to the outer function's variables, such as the URL, even after the outer function has finished executing.

  • What is the key takeaway from the video about closures?

    -The key takeaway from the video is that closures in JavaScript allow an inner function to have access to the variables and scope of an outer function, even after the outer function has finished executing.

Outlines

00:00

📘 Introduction to Closures in JavaScript

In this introductory segment, Kyle from Web Dev Simplified explains the concept of closures in JavaScript. He begins by demonstrating a simple JavaScript code example that uses a global variable and a function to print a name, which is a basic form of a closure. Kyle clarifies that closures allow functions to access variables from their outer scope, even after the outer function has finished executing. He also touches on the dynamic nature of closures, showing how they update to reflect the most recent value of a variable. The explanation is aimed at simplifying the understanding of closures, which are often misunderstood due to their more complex use cases.

05:00

🔄 Practical Use of Closures with Functions and Promises

This paragraph delves into the practical applications of closures, focusing on their use within functions that return other functions. Kyle illustrates this with an example of an 'outer function' that returns an 'inner function' and demonstrates how the inner function maintains access to the outer function's variables, a key feature of closures. He further explains how closures work with asynchronous operations, such as those involving promises with Axios or fetch, where an inner function can access variables from the outer function's scope even after the outer function has completed. The summary emphasizes the importance of closures in creating encapsulated and reusable code, particularly in scenarios involving asynchronous operations.

Mindmap

Keywords

💡Closures

Closures are a fundamental concept in JavaScript that allow a function to have access to its own scope, the outer function's scope, and the global scope, even after the outer function has completed execution. In the video, closures are introduced as a simple yet powerful feature that enables functions to 'remember' the environment in which they were created. An example given is a function that prints a name, which continues to have access to a variable defined in the outer scope, demonstrating how closures work in practice.

💡Scope

Scope refers to the accessibility of variables within different parts of a program. In JavaScript, every function creates a new scope. The video explains that closures allow functions to access variables from their outer scope, which is crucial for understanding how closures function. The script mentions 'outer scope' and 'entire JavaScript file' as different levels of scope that closures can access.

💡Global Variable

A global variable is a variable that is defined outside of all functions and is accessible from any scope within the JavaScript code. In the context of the video, the global variable 'my name' is used to demonstrate how closures enable a function to access and modify a global variable, even after the function has been defined.

💡Function

A function is a block of code designed to perform a specific task, which can be called by using its name followed by parentheses. The video script uses functions to illustrate closures, showing that functions can access variables from their outer scope. The 'print name' function in the script is an example of how a function can utilize a closure to access an outer variable.

💡Inner Function

An inner function is a function defined within another function. The video explains that inner functions have access to the variables of their outer function due to closures. This is demonstrated with an 'outer function' that returns an 'inner function', which can access the 'outer variable' even after the outer function has finished executing.

💡Outer Function

An outer function is a function that contains another function within it. In the video, the concept of an outer function is used to explain how closures allow the inner function to access its variables. The 'outer function' in the script sets an 'outer variable', which is then accessible by the returned 'inner function'.

💡Variable

A variable is a storage location paired with an associated symbolic name, containing some known or unknown quantity of information referred to as a value. The video script discusses how variables, such as 'my name' and 'outer variable', are used in closures to demonstrate the concept of functions accessing and modifying variables from their outer scope.

💡Live Value

The live value of a variable refers to its most current value at any given moment in the program's execution. The video explains that closures capture the live value of a variable at the time the inner function is called, not just the value at the time the function was defined. This is shown when 'my name' is changed to 'Joey' and the function still prints the updated value.

💡Axios/Fetch

Axios and Fetch are libraries and a web API, respectively, used to make HTTP requests from a web page. The video script mentions these as examples of where closures might be used in practice, such as within a function that handles a fetch request, where an inner function can access variables set in the outer function, like the URL being fetched.

💡Promise

A promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation. In the video, a promise is used in the context of a fetch request, where the video script explains that an inner function can access the outer scope variables even after the outer function has completed, which is a common use case for closures in handling asynchronous operations.

Highlights

Closures in JavaScript allow functions to access variables from their outer scope even after the outer function has finished executing.

The concept of closures is often misunderstood but is actually quite simple to grasp once explained.

A basic example of a closure is a function that prints a name, which in this case is 'Kyle', using a variable defined outside the function.

Closures demonstrate that JavaScript functions have access to the outer scope, including global variables.

Changing the value of an outer variable after a function has been defined affects the function's output, showing it captures the most recent value.

Closures are not just limited to accessing variables; they also allow functions to access other functions defined in their outer scope.

An 'outer function' returning an 'inner function' is a common use case for closures, where the inner function retains access to the outer variable.

The inner function 'saves' the outer variable, ensuring access to its value even after the outer function has completed execution.

Closures are useful for creating private variables within functions, as they encapsulate the outer scope's variables.

Functions defined within other functions have access to all parent scopes, including variables and other functions.

The video provides an example of using closures with asynchronous operations like fetching data from a URL.

Closures are particularly useful in scenarios involving promises and callbacks, where access to outer scope variables is necessary.

Arrow functions, despite their different syntax, also exhibit closure behavior, maintaining access to the outer scope.

The video simplifies the understanding of closures by demonstrating them with practical examples and clear explanations.

Closures enable the creation of functions with 'memory', remembering the state of variables from their outer scope.

The video concludes by emphasizing that closures are about functions having access to the scope of their outer function, regardless of when they are called.

Transcripts

play00:00

hello everyone in today's video I'm

play00:02

gonna be explaining to you exactly what

play00:05

closures are and you'll be surprised how

play00:07

simple they are to understand once you

play00:10

wrap your head around the idea so let's

play00:12

get started now welcome back to web dev

play00:18

simplified my name is Kyle and my job is

play00:21

to simplify the web for you so if that

play00:23

sounds interesting make sure you

play00:25

subscribe to the channel for more videos

play00:27

just like this one and now to get

play00:29

started I just have really simple

play00:31

JavaScript on the left side here and

play00:32

then the output showing up on the

play00:34

right-hand side and this is very simple

play00:36

code we have a variable called my name a

play00:39

function called print name which prints

play00:41

out our name whenever we call it and

play00:42

then we're calling that function and as

play00:44

you can see we're getting Kyle printed

play00:45

out over here on the side and what you

play00:48

probably don't realize is this is using

play00:50

closures this entire thing is one giant

play00:53

closure and that's because most of the

play00:55

time when you run code in other

play00:57

languages for example you cannot access

play01:00

variables outside of a function inside

play01:03

of that function that is just not always

play01:05

possible in other languages but it is

play01:07

possible in JavaScript and it is what we

play01:10

call a closure so this variable that is

play01:12

external to this function is actually

play01:14

available internally inside this

play01:16

function this is a global variable

play01:18

essentially and it's available inside

play01:21

this function and the way closures work

play01:23

in JavaScript is that every scope so for

play01:26

example we have the entire JavaScript

play01:28

file that is one scope and then our

play01:31

function is another scope so every scope

play01:33

has access to everything outside of its

play01:36

scope so our function has an outer scope

play01:39

of our entire file so it has access to

play01:41

everything inside the outer file and one

play01:44

thing that's really interesting if we

play01:46

change this here to a variable that can

play01:48

be renamed so we have our name as Kyle

play01:51

up here and we change our name down here

play01:53

we'll just say that the new name is

play01:55

going to be Joey and we save that you

play01:57

can see this now prints out Joey and so

play02:00

it's not just taking the name that is

play02:02

defined when the function is defined

play02:03

it's actually taking the current live

play02:06

value of that name it goes for example

play02:09

if we have the name here and then we

play02:11

come down here change

play02:12

- something else will change it decayed

play02:15

and then we print out the name one more

play02:18

time you can see that it says Joey and

play02:20

then Kate it's constantly going with

play02:22

whatever the most recent value of that

play02:25

variable is and now this right here is

play02:27

not the most useful way that you can use

play02:30

closures I mean it obviously is a way

play02:32

you can use them but when most people

play02:33

think of closers they think of functions

play02:36

inside of other functions so let me jump

play02:38

to another example now so here is the

play02:41

more common use case of closures where

play02:44

most people talk about closures and as

play02:46

you can see we have a function here

play02:48

called outer function and that function

play02:50

is returning another function inside of

play02:52

it called inner function and as you can

play02:55

see down here we're calling outer

play02:56

function with the variable outside so

play02:58

now we are getting a new function and

play03:00

then lastly we're calling that new

play03:01

function with the variable inside so

play03:04

what's happening is that when we first

play03:05

call this outer function we have this

play03:07

outer variable which we set to outside

play03:09

which gets set and then we have this

play03:11

function that gets returned here and the

play03:13

reason we're able to access this outer

play03:15

variable inside of this function is

play03:17

because of closures and now it's kind of

play03:20

weird when you think about it at first

play03:22

because this outer function runs and

play03:24

this outer variable is only available

play03:25

inside this function but this function

play03:28

is done executing for example if we just

play03:30

remove this code here you can see

play03:32

nothing prints out and that's because we

play03:33

call this outer function right here and

play03:35

it executes all of the code and then

play03:37

it's done executing and this outer

play03:39

variable is no longer accessible for

play03:41

example I can't log out the outer

play03:43

variable if I try to it's just gonna

play03:46

give me an error as you can see it

play03:47

doesn't actually exist so how is the

play03:50

inner function able to access this outer

play03:52

variable even after it's done being

play03:54

executed because the outer variable has

play03:57

gone out of scope and that is where

play03:59

closures come in so what happens is this

play04:01

inner function is essentially saying

play04:03

okay I'm inside this outer function it

play04:06

has this outer variable so I'm going to

play04:08

save this outer variable I'm going to

play04:10

make sure I know what this outer

play04:11

variable is at all times

play04:12

and even if the function that defined

play04:14

this variable is no longer

play04:16

I'm executed anymore it exits out of the

play04:18

function it's okay I'm still going to

play04:20

keep track of the outer variable and

play04:22

that's why you can see outer is being

play04:24

printed out outside here and we had

play04:26

in a variable also being printed out if

play04:28

I for example passing an inner variable

play04:30

you can see it gets printed out right

play04:32

there and the most common use case for

play04:34

this a lot of times is to have variables

play04:36

that you pass into functions that can be

play04:38

accessed inside of other functions we

play04:41

can also create a variable inside of

play04:42

here we're going to call this outer two

play04:44

and we're going to set this equal to

play04:46

high and we can also log that inside of

play04:49

here so we can say console dot log I

play04:51

would over to and you can see high is

play04:53

being printed out again this is inside

play04:55

the scope that is outside this function

play04:58

so this function is contained inside

play05:00

this function so everything in the outer

play05:02

function is available inside the inner

play05:04

function since in JavaScript anything on

play05:07

the inside has access to the things on

play05:08

the outside of its scope essentially it

play05:10

has access to its parent scope its

play05:12

parents parent scope and so on

play05:13

everything that is outside of it and it

play05:16

has access of course to the things

play05:17

inside of it now this here is a fairly

play05:19

contrived example so probably one of the

play05:21

more common use cases where you're going

play05:23

to see this is if you're using something

play05:25

like Axios or fetch so if we come in

play05:28

here and we have a function that's going

play05:29

to do fetch so we want to fetch you know

play05:33

for example some URL so we're gonna just

play05:35

say you know URL whatever it is some

play05:37

random URL that you're fetching and then

play05:39

inside of here you're going to have an

play05:42

actual promise that's being returned so

play05:44

we can say dot been and this is going to

play05:45

take a function and this function is a

play05:48

function that's inside our outer

play05:49

function and inside of here we would

play05:52

have access to our outer variable so we

play05:54

could say outer variable for example and

play05:56

in most cases we'd probably pass in the

play05:58

URL here and we pass it in here and

play06:01

again we'd have access to that URL

play06:03

inside this inner function and now

play06:05

obviously this looks a bit different

play06:06

this is an arrow function not a standard

play06:08

function but either way it's still a

play06:10

function defined inside of another

play06:12

function and this inner function has

play06:15

access to all of the scope of this outer

play06:17

function so it has access to this URL

play06:20

variable even though this fetch is only

play06:23

going to call this dot vend function

play06:24

long after outer function is done being

play06:27

called really all you need to know about

play06:29

closures is that when you have a

play06:31

function defined inside of another

play06:33

function like this that inner function

play06:35

has access to the variables and scope of

play06:37

the outer function E

play06:39

if the outer function finishes executing

play06:41

and those variables are no longer

play06:42

accessible outside that function so if

play06:45

you enjoyed that video make sure to

play06:47

check out my other videos linked over

play06:48

here and subscribe to the channel for

play06:51

more videos just like this one thank you

play06:53

very much for watching and have a good

play06:55

day

Rate This

5.0 / 5 (0 votes)

Related Tags
JavaScriptClosuresWeb DevelopmentScopeFunctionsVariablesProgrammingEducationalTutorialClosure Concept