What is a JavaScript Closure? Learn the how closures allow functions to "remember" outside their local scope https://fireship.io/tags/javascript/

#js #programming #100SecondsOfCode

🔗 Resources

MDN Docs https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
My Favorite Closure Explanation https://stackoverflow.com/a/36879264/3808414
Interview Question https://dmitripavlutin.com/simple-but-tricky-javascript-interview-questions/

 🤓 Install the quiz app

iOS https://itunes.apple.com/us/app/fireship/id1462592372?mt=8
Android https://play.google.com/store/apps/details?id=io.fireship.quizapp

🔥 Watch more with Fireship PRO

Upgrade to Fireship PRO at https://fireship.io/pro
Use code lORhwXd2 for 25% off your first payment. 

🎨 My Editor Settings

- Atom One Dark 
- vscode-icons
- Fira Code Font
2024-02-04T14:05:14.716Z
nova-2
2-general-nova
2024-01-09.29447
30089e05-99d1-4376-b32e-c263170674af
910db77d-5cee-419d-b565-1efa5c132bc8
5189cd78cc44e047526d71014c88928615a6777b521a1f6706d8b8de27ff6ec8
67875a7f-c9c4-48a0-aa55-5bdb8a91c34a
deprecated
JavaScript closures are functions that can access values outside of their own curly braces.
In order to call a function in your code, the JavaScript interpreter needs to know about the function itself and any other data from the surrounding environment that it depends on.
Everything needs to be neatly closed up into box, before it can be fed into the machine.
Take for example a pure function that only depends on its own arguments and internal data.
What we have here is a fully self contained closed expression.
When it's called, it gets pushed onto the call stack where it's executed and its internal data is only kept in memory until it's popped back off the call stack.
But what if that function references data outside of its own scope, like from the global environment or an outer function?
That leaves us with an open expression that references other free variables throughout the environment.
Now, in order for the interpreter to call this function and also know the value of these free variables, it creates a closure 2 store them in a place in memory where they can be accessed later.
That area of memory is called the heap, and unlike the call stack, which is short lived, it can keep data in memory indefinitely, then then decide when to get rid of it later with the garbage collector.
So a closure is not just a function, it's a function combined with its outer state or lexical environment.
As you might imagine, closures require more memory and processing power than a pure function, but you'll come across many practical reasons to use them.
The most important one being data encapsulation to prevent leaking or exposing data where it's not needed.
We can create a closure by defining an outer shan that contains the state, then an inner function that operates on it.
The data contained here will not leak out to the surrounding environment.
The inner function has access to data defined in the outer function scope.
But the outer function does not have access to the inner function.
In addition, many JavaScript APIs are callback based.
You can use closures This to create a function factory that takes an argument, then returns a brand new function, which can then be passed along to other functions that expect a callback.
This has been JavaScript have closures in 100 seconds.
But stay tuned, because today, we're going beyond 100 seconds to take a look at one of the most famous JavaScript trick questions that will wreck you on an interview if you don't know closures.
But, first, make sure to like and subscribe.
I'm trying to fulfill my childhood dream of getting to a 1000000 subscribers, but it's going to be really hard to get there if you don't click the button.
Just kidding.
I have a ton of fun making these videos and learn something new every time.
A great example of which is this tricky JavaScript interview question.
The question itself is what does this code log out?
Let's go through it line by line.
First, we're declaring a variable I with the var keyword, then a for loop that will run 3 times by incrementing that variable.
Now inside the for loop is where closures come into play.
We define a function log that console logs the global variable I.
This is not a pure function because it depends on a variable outside of its scope, therefore creating a closure.
Then, from there, we set up a timeout and pass the log function as the callback.
This queues up a task to execute the log function after 100 milliseconds.
So what do you think the output of this code will be?
We're capturing the I variable in the closure for each iteration of a loop, so it would seem like it should log out 0, 1, 2.
But if we log it out, it actually console logs 3, three times.
To understand why that happens, we also need to understand the difference between var and let.
When you use var in a for loop, that variable actually gets hoisted up into the parent scope, which in this case would be the global scope.
Watch what happens when we change the variable let, we get our original expectation of a console log of 0, 12.
With var, we have a global variable that we're mutating over and over again, But, with let, we're creating a variable that is scoped to the for loop.
In other words, it's local to the for loop and can't be accessed outside of it.
Now remember, a closure is the combination of a function and its lexical environment.
In the case of let, the closure is capturing the log function along with the variable I for each iteration of the loop, which would be 012.
If we didn't have a closure here, JavaScript would allocate that I variable in memory in the call stack and then immediately release it.
But because we do have a closure, it stores that variable in the heap memory, so it can be referenced again when that closure is called by the time out in the future.
But when var is used, it's capturing the reference to the global variable.
The reason it logs 3 three times is because the timeout doesn't run till a 100 milliseconds later, long after that for loop has completed and iterated up to 3.
We can actually examine this behavior in the browser dev tools by adding then a debugger to the closure.
If you try to run this code in the browser with the dev tools open, it will take you to the sources tab and allow you to inspect the call stack and scope of the function.
When let is you can see we have a block scoped variable named I, but when bar is used, that variable is now in the global scope, which changes the way it's captured by the closure.
That's a pretty tricky one, but JavaScript interviewers love to ask questions like this.
If you ever find yourself faced with a question like this, the best thing you can do is talk through the code slowly and explain how a closure works, so they know you're on the right track even if you don't come to the right conclusion.
I'm gonna go ahead and wrap things up there.
Thanks for watching, and I will see you in the next one.

Speaker 0: JavaScript closures are functions that can access values outside of their own curly braces. In order to call a function in your code, the JavaScript interpreter needs to know about the function itself and any other data from the surrounding environment that it depends on. Everything needs to be neatly closed up into box, before it can be fed into the machine. Take for example a pure function that only depends on its own arguments and internal data. What we have here is a fully self contained closed expression.

When it's called, it gets pushed onto the call stack where it's executed and its internal data is only kept in memory until it's popped back off the call stack. But what if that function references data outside of its own scope, like from the global environment or an outer function? That leaves us with an open expression that references other free variables throughout the environment. Now, in order for the interpreter to call this function and also know the value of these free variables, it creates a closure 2 store them in a place in memory where they can be accessed later. That area of memory is called the heap, and unlike the call stack, which is short lived, it can keep data in memory indefinitely, then then decide when to get rid of it later with the garbage collector.

So a closure is not just a function, it's a function combined with its outer state or lexical environment. As you might imagine, closures require more memory and processing power than a pure function, but you'll come across many practical reasons to use them. The most important one being data encapsulation to prevent leaking or exposing data where it's not needed. We can create a closure by defining an outer shan that contains the state, then an inner function that operates on it. The data contained here will not leak out to the surrounding environment.

The inner function has access to data defined in the outer function scope. But the outer function does not have access to the inner function. In addition, many JavaScript APIs are callback based. You can use closures This to create a function factory that takes an argument, then returns a brand new function, which can then be passed along to other functions that expect a callback. This has been JavaScript have closures in 100 seconds.

But stay tuned, because today, we're going beyond 100 seconds to take a look at one of the most famous JavaScript trick questions that will wreck you on an interview if you don't know closures. But, first, make sure to like and subscribe. I'm trying to fulfill my childhood dream of getting to a 1000000 subscribers, but it's going to be really hard to get there if you don't click the button. Just kidding. I have a ton of fun making these videos and learn something new every time.

A great example of which is this tricky JavaScript interview question. The question itself is what does this code log out? Let's go through it line by line. First, we're declaring a variable I with the var keyword, then a for loop that will run 3 times by incrementing that variable. Now inside the for loop is where closures come into play.

We define a function log that console logs the global variable I. This is not a pure function because it depends on a variable outside of its scope, therefore creating a closure. Then, from there, we set up a timeout and pass the log function as the callback. This queues up a task to execute the log function after 100 milliseconds. So what do you think the output of this code will be?

We're capturing the I variable in the closure for each iteration of a loop, so it would seem like it should log out 0, 1, 2. But if we log it out, it actually console logs 3, three times. To understand why that happens, we also need to understand the difference between var and let. When you use var in a for loop, that variable actually gets hoisted up into the parent scope, which in this case would be the global scope. Watch what happens when we change the variable let, we get our original expectation of a console log of 0, 12.

With var, we have a global variable that we're mutating over and over again, But, with let, we're creating a variable that is scoped to the for loop. In other words, it's local to the for loop and can't be accessed outside of it. Now remember, a closure is the combination of a function and its lexical environment. In the case of let, the closure is capturing the log function along with the variable I for each iteration of the loop, which would be 012. If we didn't have a closure here, JavaScript would allocate that I variable in memory in the call stack and then immediately release it.

But because we do have a closure, it stores that variable in the heap memory, so it can be referenced again when that closure is called by the time out in the future. But when var is used, it's capturing the reference to the global variable. The reason it logs 3 three times is because the timeout doesn't run till a 100 milliseconds later, long after that for loop has completed and iterated up to 3. We can actually examine this behavior in the browser dev tools by adding then a debugger to the closure. If you try to run this code in the browser with the dev tools open, it will take you to the sources tab and allow you to inspect the call stack and scope of the function.

When let is you can see we have a block scoped variable named I, but when bar is used, that variable is now in the global scope, which changes the way it's captured by the closure. That's a pretty tricky one, but JavaScript interviewers love to ask questions like this. If you ever find yourself faced with a question like this, the best thing you can do is talk through the code slowly and explain how a closure works, so they know you're on the right track even if you don't come to the right conclusion. I'm gonna go ahead and wrap things up there. Thanks for watching, and I will see you in the next one.
JavaScript closures are functions that can access values outside of their own curly braces. In order to call a function in your code, the JavaScript interpreter needs to know about the function itself and any other data from the surrounding environment that it depends on.
Everything needs to be neatly closed up into box, before it can be fed into the machine. Take for example a pure function that only depends on its own arguments and internal data. What we have here is a fully self contained closed expression. When it's called, it gets pushed onto the call stack where it's executed and its internal data is only kept in memory until it's popped back off the call stack. But what if that function references data outside of its own scope, like from the global environment or an outer function?
programming
logic
That leaves us with an open expression that references other free variables throughout the environment. Now, in order for the interpreter to call this function and also know the value of these free variables, it creates a closure 2 store them in a place in memory where they can be accessed later. That area of memory is called the heap, and unlike the call stack, which is short lived, it can keep data in memory indefinitely, then then decide when to get rid of it later with the garbage collector. So a closure is not just a function, it's a function combined with its outer state or lexical environment. As you might imagine, closures require more memory and processing power than a pure function, but you'll come across many practical reasons to use them.
The most important one being data encapsulation to prevent leaking or exposing data where it's not needed. We can create a closure by defining an outer shan that contains the state, then an inner function that operates on it. The data contained here will not leak out to the surrounding environment.
data management
data
The inner function has access to data defined in the outer function scope. But the outer function does not have access to the inner function. In addition, many JavaScript APIs are callback based. You can use closures This to create a function factory that takes an argument, then returns a brand new function, which can then be passed along to other functions that expect a callback. This has been JavaScript have closures in 100 seconds. But stay tuned, because today, we're going beyond 100 seconds to take a look at one of the most famous JavaScript trick questions that will wreck you on an interview if you don't know closures.
But, first, make sure to like and subscribe. I'm trying to fulfill my childhood dream of getting to a 1000000 subscribers, but it's going to be really hard to get there if you don't click the button. Just kidding. I have a ton of fun making these videos and learn something new every time. A great example of which is this tricky JavaScript interview question. The question itself is what does this code log out? Let's go through it line by line. First, we're declaring a variable I with the var keyword, then a for loop that will run 3 times by incrementing that variable. Now inside the for loop is where closures come into play. We define a function log that console logs the global variable I. This is not a pure function because it depends on a variable outside of its scope, therefore creating a closure. Then, from there, we set up a timeout and pass the log function as the callback. This queues up a task to execute the log function after 100 milliseconds. So what do you think the output of this code will be? We're capturing the I variable in the closure for each iteration of a loop, so it would seem like it should log out 0, 1, 2. But if we log it out, it actually console logs 3, three times.
youtube
podcasts
programming
netflix
streaming
video gaming
To understand why that happens, we also need to understand the difference between var and let. When you use var in a for loop, that variable actually gets hoisted up into the parent scope, which in this case would be the global scope.
Watch what happens when we change the variable let, we get our original expectation of a console log of 0, 12. With var, we have a global variable that we're mutating over and over again, But, with let, we're creating a variable that is scoped to the for loop. In other words, it's local to the for loop and can't be accessed outside of it.
programming
Now remember, a closure is the combination of a function and its lexical environment. In the case of let, the closure is capturing the log function along with the variable I for each iteration of the loop, which would be 012. If we didn't have a closure here, JavaScript would allocate that I variable in memory in the call stack and then immediately release it. But because we do have a closure, it stores that variable in the heap memory, so it can be referenced again when that closure is called by the time out in the future. But when var is used, it's capturing the reference to the global variable. The reason it logs 3 three times is because the timeout doesn't run till a 100 milliseconds later, long after that for loop has completed and iterated up to 3. We can actually examine this behavior in the browser dev tools by adding then a debugger to the closure. If you try to run this code in the browser with the dev tools open, it will take you to the sources tab and allow you to inspect the call stack and scope of the function.
When let is you can see we have a block scoped variable named I, but when bar is used, that variable is now in the global scope, which changes the way it's captured by the closure. That's a pretty tricky one, but JavaScript interviewers love to ask questions like this.
programming
If you ever find yourself faced with a question like this, the best thing you can do is talk through the code slowly and explain how a closure works, so they know you're on the right track even if you don't come to the right conclusion. I'm gonna go ahead and wrap things up there. Thanks for watching, and I will see you in the next one.
JavaScript closures are functions that can access values outside of their own curly braces. In order to call a function in your code, the JavaScript interpreter needs to know about the function itself and any other data from the surrounding environment that it depends on. Everything needs to be neatly closed up into box, before it can be fed into the machine. Take for example a pure function that only depends on its own arguments and internal data. What we have here is a fully self contained closed expression. When it's called, it gets pushed onto the call stack where it's executed and its internal data is only kept in memory until it's popped back off the call stack. But what if that function references data outside of its own scope, like from the global environment or an outer function? That leaves us with an open expression that references other free variables throughout the environment. Now, in order for the interpreter to call this function and also know the value of these free variables, it creates a closure 2 store them in a place in memory where they can be accessed later. That area of memory is called the heap, and unlike the call stack, which is short lived, it can keep data in memory indefinitely, then then decide when to get rid of it later with the garbage collector. So a closure is not just a function, it's a function combined with its outer state or lexical environment. As you might imagine, closures require more memory and processing power than a pure function, but you'll come across many practical reasons to use them. The most important one being data encapsulation to prevent leaking or exposing data where it's not needed. We can create a closure by defining an outer shan that contains the state, then an inner function that operates on it. The data contained here will not leak out to the surrounding environment. The inner function has access to data defined in the outer function scope. But the outer function does not have access to the inner function. In addition, many JavaScript APIs are callback based. You can use closures This to create a function factory that takes an argument, then returns a brand new function, which can then be passed along to other functions that expect a callback. This has been JavaScript have closures in 100 seconds. But stay tuned, because today, we're going beyond 100 seconds to take a look at one of the most famous JavaScript trick questions that will wreck you on an interview if you don't know closures. But, first, make sure to like and subscribe. I'm trying to fulfill my childhood dream of getting to a 1000000 subscribers, but it's going to be really hard to get there if you don't click the button. Just kidding. I have a ton of fun making these videos and learn something new every time. A great example of which is this tricky JavaScript interview question. The question itself is what does this code log out? Let's go through it line by line. First, we're declaring a variable I with the var keyword, then a for loop that will run 3 times by incrementing that variable. Now inside the for loop is where closures come into play. We define a function log that console logs the global variable I. This is not a pure function because it depends on a variable outside of its scope, therefore creating a closure. Then, from there, we set up a timeout and pass the log function as the callback. This queues up a task to execute the log function after 100 milliseconds. So what do you think the output of this code will be? We're capturing the I variable in the closure for each iteration of a loop, so it would seem like it should log out 0, 1, 2. But if we log it out, it actually console logs 3, three times. To understand why that happens, we also need to understand the difference between var and let. When you use var in a for loop, that variable actually gets hoisted up into the parent scope, which in this case would be the global scope. Watch what happens when we change the variable let, we get our original expectation of a console log of 0, 12. With var, we have a global variable that we're mutating over and over again, But, with let, we're creating a variable that is scoped to the for loop. In other words, it's local to the for loop and can't be accessed outside of it. Now remember, a closure is the combination of a function and its lexical environment. In the case of let, the closure is capturing the log function along with the variable I for each iteration of the loop, which would be 012. If we didn't have a closure here, JavaScript would allocate that I variable in memory in the call stack and then immediately release it. But because we do have a closure, it stores that variable in the heap memory, so it can be referenced again when that closure is called by the time out in the future. But when var is used, it's capturing the reference to the global variable. The reason it logs 3 three times is because the timeout doesn't run till a 100 milliseconds later, long after that for loop has completed and iterated up to 3. We can actually examine this behavior in the browser dev tools by adding then a debugger to the closure. If you try to run this code in the browser with the dev tools open, it will take you to the sources tab and allow you to inspect the call stack and scope of the function. When let is you can see we have a block scoped variable named I, but when bar is used, that variable is now in the global scope, which changes the way it's captured by the closure. That's a pretty tricky one, but JavaScript interviewers love to ask questions like this. If you ever find yourself faced with a question like this, the best thing you can do is talk through the code slowly and explain how a closure works, so they know you're on the right track even if you don't come to the right conclusion. I'm gonna go ahead and wrap things up there. Thanks for watching, and I will see you in the next one.
JavaScript
javascript
closures
closures
are
are
functions
functions
that
that
can
can
access
access
values
values
outside
outside
of
of
their
their
own
own
curly
curly
braces.
braces
In
in
order
order
to
to
call
call
a
a
function
function
in
in
your
your
code,
code
the
the
JavaScript
javascript
interpreter
interpreter
needs
needs
to
to
know
know
about
about
the
the
function
function
itself
itself
and
and
any
any
other
other
data
data
from
from
the
the
surrounding
surrounding
environment
environment
that
that
it
it
depends
depends
on.
on
Everything
everything
needs
needs
to
to
be
be
neatly
neatly
closed
closed
up
up
into
into
box,
box
before
before
it
it
can
can
be
be
fed
fed
into
into
the
the
machine.
machine
Take
take
for
for
example
example
a
a
pure
pure
function
function
that
that
only
only
depends
depends
on
on
its
its
own
own
arguments
arguments
and
and
internal
internal
data.
data
What
what
we
we
have
have
here
here
is
is
a
a
fully
fully
self
self
contained
contained
closed
closed
expression.
expression
When
when
it's
it's
called,
called
it
it
gets
gets
pushed
pushed
onto
onto
the
the
call
call
stack
stack
where
where
it's
it's
executed
executed
and
and
its
its
internal
internal
data
data
is
is
only
only
kept
kept
in
in
memory
memory
until
until
it's
it's
popped
popped
back
back
off
off
the
the
call
call
stack.
stack
But
but
what
what
if
if
that
that
function
function
references
references
data
data
outside
outside
of
of
its
its
own
own
scope,
scope
like
like
from
from
the
the
global
global
environment
environment
or
or
an
an
outer
outer
function?
function
That
that
leaves
leaves
us
us
with
with
an
an
open
open
expression
expression
that
that
references
references
other
other
free
free
variables
variables
throughout
throughout
the
the
environment.
environment
Now,
now
in
in
order
order
for
for
the
the
interpreter
interpreter
to
to
call
call
this
this
function
function
and
and
also
also
know
know
the
the
value
value
of
of
these
these
free
free
variables,
variables
it
it
creates
creates
a
a
closure
closure
2
2
store
store
them
them
in
in
a
a
place
place
in
in
memory
memory
where
where
they
they
can
can
be
be
accessed
accessed
later.
later
That
that
area
area
of
of
memory
memory
is
is
called
called
the
the
heap,
heap
and
and
unlike
unlike
the
the
call
call
stack,
stack
which
which
is
is
short
short
lived,
lived
it
it
can
can
keep
keep
data
data
in
in
memory
memory
indefinitely,
indefinitely
then
then
then
then
decide
decide
when
when
to
to
get
get
rid
rid
of
of
it
it
later
later
with
with
the
the
garbage
garbage
collector.
collector
So
so
a
a
closure
closure
is
is
not
not
just
just
a
a
function,
function
it's
it's
a
a
function
function
combined
combined
with
with
its
its
outer
outer
state
state
or
or
lexical
lexical
environment.
environment
As
as
you
you
might
might
imagine,
imagine
closures
closures
require
require
more
more
memory
memory
and
and
processing
processing
power
power
than
than
a
a
pure
pure
function,
function
but
but
you'll
you'll
come
come
across
across
many
many
practical
practical
reasons
reasons
to
to
use
use
them.
them
The
the
most
most
important
important
one
one
being
being
data
data
encapsulation
encapsulation
to
to
prevent
prevent
leaking
leaking
or
or
exposing
exposing
data
data
where
where
it's
it's
not
not
needed.
needed
We
we
can
can
create
create
a
a
closure
closure
by
by
defining
defining
an
an
outer
outer
shan
shan
that
that
contains
contains
the
the
state,
state
then
then
an
an
inner
inner
function
function
that
that
operates
operates
on
on
it.
it
The
the
data
data
contained
contained
here
here
will
will
not
not
leak
leak
out
out
to
to
the
the
surrounding
surrounding
environment.
environment
The
the
inner
inner
function
function
has
has
access
access
to
to
data
data
defined
defined
in
in
the
the
outer
outer
function
function
scope.
scope
But
but
the
the
outer
outer
function
function
does
does
not
not
have
have
access
access
to
to
the
the
inner
inner
function.
function
In
in
addition,
addition
many
many
JavaScript
javascript
APIs
apis
are
are
callback
callback
based.
based
You
you
can
can
use
use
closures
closures
This
this
to
to
create
create
a
a
function
function
factory
factory
that
that
takes
takes
an
an
argument,
argument
then
then
returns
returns
a
a
brand
brand
new
new
function,
function
which
which
can
can
then
then
be
be
passed
passed
along
along
to
to
other
other
functions
functions
that
that
expect
expect
a
a
callback.
callback
This
this
has
has
been
been
JavaScript
javascript
have
have
closures
closures
in
in
100
100
seconds.
seconds
But
but
stay
stay
tuned,
tuned
because
because
today,
today
we're
we're
going
going
beyond
beyond
100
100
seconds
seconds
to
to
take
take
a
a
look
look
at
at
one
one
of
of
the
the
most
most
famous
famous
JavaScript
javascript
trick
trick
questions
questions
that
that
will
will
wreck
wreck
you
you
on
on
an
an
interview
interview
if
if
you
you
don't
don't
know
know
closures.
closures
But,
but
first,
first
make
make
sure
sure
to
to
like
like
and
and
subscribe.
subscribe
I'm
i'm
trying
trying
to
to
fulfill
fulfill
my
my
childhood
childhood
dream
dream
of
of
getting
getting
to
to
a
a
1000000
1000000
subscribers,
subscribers
but
but
it's
it's
going
going
to
to
be
be
really
really
hard
hard
to
to
get
get
there
there
if
if
you
you
don't
don't
click
click
the
the
button.
button
Just
just
kidding.
kidding
I
i
have
have
a
a
ton
ton
of
of
fun
fun
making
making
these
these
videos
videos
and
and
learn
learn
something
something
new
new
every
every
time.
time
A
a
great
great
example
example
of
of
which
which
is
is
this
this
tricky
tricky
JavaScript
javascript
interview
interview
question.
question
The
the
question
question
itself
itself
is
is
what
what
does
does
this
this
code
code
log
log
out?
out
Let's
let's
go
go
through
through
it
it
line
line
by
by
line.
line
First,
first
we're
we're
declaring
declaring
a
a
variable
variable
I
i
with
with
the
the
var
var
keyword,
keyword
then
then
a
a
for
for
loop
loop
that
that
will
will
run
run
3
3
times
times
by
by
incrementing
incrementing
that
that
variable.
variable
Now
now
inside
inside
the
the
for
for
loop
loop
is
is
where
where
closures
closures
come
come
into
into
play.
play
We
we
define
define
a
a
function
function
log
log
that
that
console
console
logs
logs
the
the
global
global
variable
variable
I.
i
This
this
is
is
not
not
a
a
pure
pure
function
function
because
because
it
it
depends
depends
on
on
a
a
variable
variable
outside
outside
of
of
its
its
scope,
scope
therefore
therefore
creating
creating
a
a
closure.
closure
Then,
then
from
from
there,
there
we
we
set
set
up
up
a
a
timeout
timeout
and
and
pass
pass
the
the
log
log
function
function
as
as
the
the
callback.
callback
This
this
queues
queues
up
up
a
a
task
task
to
to
execute
execute
the
the
log
log
function
function
after
after
100
100
milliseconds.
milliseconds
So
so
what
what
do
do
you
you
think
think
the
the
output
output
of
of
this
this
code
code
will
will
be?
be
We're
we're
capturing
capturing
the
the
I
i
variable
variable
in
in
the
the
closure
closure
for
for
each
each
iteration
iteration
of
of
a
a
loop,
loop
so
so
it
it
would
would
seem
seem
like
like
it
it
should
should
log
log
out
out
0,
0
1,
1
2.
2
But
but
if
if
we
we
log
log
it
it
out,
out
it
it
actually
actually
console
console
logs
logs
3,
3
three
three
times.
times
To
to
understand
understand
why
why
that
that
happens,
happens
we
we
also
also
need
need
to
to
understand
understand
the
the
difference
difference
between
between
var
var
and
and
let.
let
When
when
you
you
use
use
var
var
in
in
a
a
for
for
loop,
loop
that
that
variable
variable
actually
actually
gets
gets
hoisted
hoisted
up
up
into
into
the
the
parent
parent
scope,
scope
which
which
in
in
this
this
case
case
would
would
be
be
the
the
global
global
scope.
scope
Watch
watch
what
what
happens
happens
when
when
we
we
change
change
the
the
variable
variable
let,
let
we
we
get
get
our
our
original
original
expectation
expectation
of
of
a
a
console
console
log
log
of
of
0,
0
12.
12
With
with
var,
var
we
we
have
have
a
a
global
global
variable
variable
that
that
we're
we're
mutating
mutating
over
over
and
and
over
over
again,
again
But,
but
with
with
let,
let
we're
we're
creating
creating
a
a
variable
variable
that
that
is
is
scoped
scoped
to
to
the
the
for
for
loop.
loop
In
in
other
other
words,
words
it's
it's
local
local
to
to
the
the
for
for
loop
loop
and
and
can't
can't
be
be
accessed
accessed
outside
outside
of
of
it.
it
Now
now
remember,
remember
a
a
closure
closure
is
is
the
the
combination
combination
of
of
a
a
function
function
and
and
its
its
lexical
lexical
environment.
environment
In
in
the
the
case
case
of
of
let,
let
the
the
closure
closure
is
is
capturing
capturing
the
the
log
log
function
function
along
along
with
with
the
the
variable
variable
I
i
for
for
each
each
iteration
iteration
of
of
the
the
loop,
loop
which
which
would
would
be
be
012.
012
If
if
we
we
didn't
didn't
have
have
a
a
closure
closure
here,
here
JavaScript
javascript
would
would
allocate
allocate
that
that
I
i
variable
variable
in
in
memory
memory
in
in
the
the
call
call
stack
stack
and
and
then
then
immediately
immediately
release
release
it.
it
But
but
because
because
we
we
do
do
have
have
a
a
closure,
closure
it
it
stores
stores
that
that
variable
variable
in
in
the
the
heap
heap
memory,
memory
so
so
it
it
can
can
be
be
referenced
referenced
again
again
when
when
that
that
closure
closure
is
is
called
called
by
by
the
the
time
time
out
out
in
in
the
the
future.
future
But
but
when
when
var
var
is
is
used,
used
it's
it's
capturing
capturing
the
the
reference
reference
to
to
the
the
global
global
variable.
variable
The
the
reason
reason
it
it
logs
logs
3
3
three
three
times
times
is
is
because
because
the
the
timeout
timeout
doesn't
doesn't
run
run
till
till
a
a
100
100
milliseconds
milliseconds
later,
later
long
long
after
after
that
that
for
for
loop
loop
has
has
completed
completed
and
and
iterated
iterated
up
up
to
to
3.
3
We
we
can
can
actually
actually
examine
examine
this
this
behavior
behavior
in
in
the
the
browser
browser
dev
dev
tools
tools
by
by
adding
adding
then
then
a
a
debugger
debugger
to
to
the
the
closure.
closure
If
if
you
you
try
try
to
to
run
run
this
this
code
code
in
in
the
the
browser
browser
with
with
the
the
dev
dev
tools
tools
open,
open
it
it
will
will
take
take
you
you
to
to
the
the
sources
sources
tab
tab
and
and
allow
allow
you
you
to
to
inspect
inspect
the
the
call
call
stack
stack
and
and
scope
scope
of
of
the
the
function.
function
When
when
let
let
is
is
you
you
can
can
see
see
we
we
have
have
a
a
block
block
scoped
scoped
variable
variable
named
named
I,
i
but
but
when
when
bar
bar
is
is
used,
used
that
that
variable
variable
is
is
now
now
in
in
the
the
global
global
scope,
scope
which
which
changes
changes
the
the
way
way
it's
it's
captured
captured
by
by
the
the
closure.
closure
That's
that's
a
a
pretty
pretty
tricky
tricky
one,
one
but
but
JavaScript
javascript
interviewers
interviewers
love
love
to
to
ask
ask
questions
questions
like
like
this.
this
If
if
you
you
ever
ever
find
find
yourself
yourself
faced
faced
with
with
a
a
question
question
like
like
this,
this
the
the
best
best
thing
thing
you
you
can
can
do
do
is
is
talk
talk
through
through
the
the
code
code
slowly
slowly
and
and
explain
explain
how
how
a
a
closure
closure
works,
works
so
so
they
they
know
know
you're
you're
on
on
the
the
right
right
track
track
even
even
if
if
you
you
don't
don't
come
come
to
to
the
the
right
right
conclusion.
conclusion
I'm
i'm
gonna
gonna
go
go
ahead
ahead
and
and
wrap
wrap
things
things
up
up
there.
there
Thanks
thanks
for
for
watching,
watching
and
and
I
i
will
will
see
see
you
you
in
in
the
the
next
next
one.
one
success
The speaker explains that JavaScript has a "price" of "price" that requires more memory and processing power than a pure function, but can be used in a "price" that references other variables outside of its own scope. They also explain the concept of "price" and how it can be used to log out of a variables in a "price" that involves capturing the log function and the variable I. They also explain the difference between var and let, and suggest using the "price" in the "price" section of the code to understand the behavior of the function.
Closures Explained in 100 Seconds // Tricky JavaScript Interview Prep
JavaScript closures are functions that can access values outside of their own curly braces. In order to call a function in your code, the JavaScript interpreter needs to know about the function itself and any other data from the surrounding environment that it depends on. Everything needs to be neatly closed up into box, before it can be fed into the machine. Take for example a pure function that only depends on its own arguments and internal data. What we have here is a fully self contained closed expression. When it's called, it gets pushed onto the call stack where it's executed and its internal data is only kept in memory until it's popped back off the call stack. But what if that function references data outside of its own scope, like from the global environment or an outer function? That leaves us with an open expression that references other free variables throughout the environment. Now, in order for the interpreter to call this function and also know the value of these free variables, it creates a closure 2 store them in a place in memory where they can be accessed later. That area of memory is called the heap, and unlike the call stack, which is short lived, it can keep data in memory indefinitely, then then decide when to get rid of it later with the garbage collector. So a closure is not just a function, it's a function combined with its outer state or lexical environment. As you might imagine, closures require more memory and processing power than a pure function, but you'll come across many practical reasons to use them. The most important one being data encapsulation to prevent leaking or exposing data where it's not needed. We can create a closure by defining an outer shan that contains the state, then an inner function that operates on it. The data contained here will not leak out to the surrounding environment. The inner function has access to data defined in the outer function scope. But the outer function does not have access to the inner function. In addition, many JavaScript APIs are callback based. You can use closures This to create a function factory that takes an argument, then returns a brand new function, which can then be passed along to other functions that expect a callback. This has been JavaScript have closures in 100 seconds. But stay tuned, because today, we're going beyond 100 seconds to take a look at one of the most famous JavaScript trick questions that will wreck you on an interview if you don't know closures. But, first, make sure to like and subscribe. I'm trying to fulfill my childhood dream of getting to a 1000000 subscribers, but it's going to be really hard to get there if you don't click the button. Just kidding. I have a ton of fun making these videos and learn something new every time. A great example of which is this tricky JavaScript interview question. The question itself is what does this code log out? Let's go through it line by line. First, we're declaring a variable I with the var keyword, then a for loop that will run 3 times by incrementing that variable. Now inside the for loop is where closures come into play. We define a function log that console logs the global variable I. This is not a pure function because it depends on a variable outside of its scope, therefore creating a closure. Then, from there, we set up a timeout and pass the log function as the callback. This queues up a task to execute the log function after 100 milliseconds. So what do you think the output of this code will be? We're capturing the I variable in the closure for each iteration of a loop, so it would seem like it should log out 0, 1, 2. But if we log it out, it actually console logs 3, three times. To understand why that happens, we also need to understand the difference between var and let. When you use var in a for loop, that variable actually gets hoisted up into the parent scope, which in this case would be the global scope. Watch what happens when we change the variable let, we get our original expectation of a console log of 0, 12. With var, we have a global variable that we're mutating over and over again, But, with let, we're creating a variable that is scoped to the for loop. In other words, it's local to the for loop and can't be accessed outside of it. Now remember, a closure is the combination of a function and its lexical environment. In the case of let, the closure is capturing the log function along with the variable I for each iteration of the loop, which would be 012. If we didn't have a closure here, JavaScript would allocate that I variable in memory in the call stack and then immediately release it. But because we do have a closure, it stores that variable in the heap memory, so it can be referenced again when that closure is called by the time out in the future. But when var is used, it's capturing the reference to the global variable. The reason it logs 3 three times is because the timeout doesn't run till a 100 milliseconds later, long after that for loop has completed and iterated up to 3. We can actually examine this behavior in the browser dev tools by adding then a debugger to the closure. If you try to run this code in the browser with the dev tools open, it will take you to the sources tab and allow you to inspect the call stack and scope of the function. When let is you can see we have a block scoped variable named I, but when bar is used, that variable is now in the global scope, which changes the way it's captured by the closure. That's a pretty tricky one, but JavaScript interviewers love to ask questions like this. If you ever find yourself faced with a question like this, the best thing you can do is talk through the code slowly and explain how a closure works, so they know you're on the right track even if you don't come to the right conclusion. I'm gonna go ahead and wrap things up there. Thanks for watching, and I will see you in the next one.
The speaker explains that JavaScript has a "price" of "price" that requires more memory and processing power than a pure function, but can be used in a "price" that references other variables outside of its own scope. They also explain the concept of "price" and how it can be used to log out of a variables in a "price" that involves capturing the log function and the variable I. They also explain the difference between var and let, and suggest using the "price" in the "price" section of the code to understand the behavior of the function.