- [Instructor] Another building block
of closures is nested functions.
In functional programming,
we often work with a set of independent functions.
In object-oriented programming,
we work with individual functions
as methods of an object.
In order to create a closure though,
we nest functions,
declaring a function within another function.
We refer to the nested function
as the inner function or the child function.
We refer to the function the inner function
is nested within
as the outer function or the parent function.
A function name has scope,
just like a variable name.
So creating a function within another function means
that the inner function has local scope
and is not available outside of the outer function.
So in the script.js start file for this video,
I'm building out our function
that stores and updates the number of times
an interface button has been clicked.
And right now, my code logs the state
of the clicks variable
after each click but I'd like my code
to be a little more organized.
So for organizational purposes,
I'm going to create a nested function
within the updateClicks function.
I'll call that reportClicks.
And in it, I'm going to create a new variable called report
whose value is an array referencing the button variable,
which is the ID of the element that was just clicked
and the clicks variable.
And then I can move my console.log statement
inside my new nested function,
and I can use the ES6 spread operator
to log both elements of the report array.
So I'll say ...report,
and that will log both of the elements in the report array.
And then finally, outside of the nested function,
but still within the updateClicks function,
I'll call that nested function.
So we'll call reportClicks.
And so now reportClicks
is my nested function, my inner function,
and my outer function is updateClicks.
And from JavaScript's scoping rules,
we know that the variables of the outer scope
are available within any nested scope.
So the reportClicks function
has access to the button variable
that's defined in the outer function, updateClicks.
And both functions have access to the clicks variable,
which is defined in the global scope.
So I'll save my changes.
I have my API key.
And I have my document loaded in the browser.
I will enter Sydney as the city.
Get the forecast.
And then as I click each button,
I see the ID of the button clicked,
as well as the full updated clicks object.
So this code leverages nested functions
and nested local scopes
to add a little more detail to our logs
while keeping our code organized.