Closures
Rules of closures
A closure grants access to the variables passed to a function after it has completed and returned.
Helps keep variables from getting pushed into global scope.
Provides a degree of protection. Variable can't be overwritten
File Location
We will be working in the following file:
Global Variables
Note below that the function is returning another function:
Take some time to analyze the functions above. Notice that the addSquares function returns the result of the square
function added together.
Also, the square
function is declared inside the scope of the addSquares
function. Couple more things to note:
The square function has access to the addSquares parameters.
square
can't be called outside the scope ofaddSquares
More sample code
Here the inner function has access to outer's variables & parameters
Couple things to notice:
The
intro
variable is used inside of themakeFull
function.printName
returns a functionmakeFull
.makeFull
is not accessible outside of theprintName
function.
These concepts are the basic building blocks of closures.
A Challenge
Here's a good challenge to try.
Create a function expression called
calculateTotalWithTip
.The function will have two parameters: totalWithoutTip & tipPercentage.
Create a totalWithTip variable within the scope of #1.
Create a function declaration called
calculateTip
in the scope of #1.The function takes in the same two parameters: totalWithoutTip & tipPercentage.
Create a variable in the
calculateTip
function calledtipAmount
.tipAmount
will hold the product of totalWithoutTip & tipPercentage.The
calculateTip
inner function returnstipAmount
.Set the
totalWithTip
variable equal to the result of runningcalculateTip
added to totalWithoutTip.Return the
totalWithTip
variable.
Last updated