- [Instructor] Closures are an inner function
that has access to external variables.
By creating a function inside of a function,
we create a closure.
So let's do some code to understand and visualize this.
So we'll leverage some of the code
that we did on the last video,
and the first thing we'll do is simply remove
the console.log here, and then do a function
inside of that function.
We'll return an object, and inside of that object
we'll have a function called shootWarrior,
which will return a console.log.
And this console.log will have warrior, and then warrior2.
So if I comment the console.log on line 15,
and I save this, and I go back to Chrome here,
I shouldn't have anything here,
so what we need to do is create another variable
from the function here, which is const,
and let's call this one newWarrior,
and then pass the function screamWarrior,
and then use newWarrior, and then run that function.
Because that function is part of an object here,
so we need to create a new variable
which holds that function,
and then be able to use the shootWarrior.
Now if I run this, and I go back here,
I should have Ninja Ninja.
And let's change this to warrior2 actually.
So I should have actually Ninja and Samurai.
So let's go back here.
So this is the expected behavior, and here's why.
Inside of that function here, we have access
to a global variable called warrior,
and inside of that function we also have access to warrior2,
because it's part of that function.
But if we run this console.log here,
we don't have access to warrior2.
So if I save that, I'm gonna have an error.
And this is normal.
So as you can see, we can access warrior2
outside of that function, which allows us
to make this variable private in some ways.
So in summary, closures are great ways
to use variables without making them global,
or accessible everywhere.
As a side note, you'll see closures used
everywhere in popular libraries
for the same reasons we've explained here.