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:
javascript-library
└── 1-Fundamentals
└── 4-Functions
07-closures.js <----You will be working in this file.Global Variables
Note below that the function is returning another function:
function addSquares(a, b) {
function square(x) {
return x * x;
}
return square(a) + square(b);
}
var a = addSquares(2, 3); // returns 13
var b = addSquares(3, 4); // returns 25
var c = addSquares(4, 5); // returns 41Take 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.
squarecan't be called outside the scope ofaddSquares
More sample code
Here the inner function has access to outer's variables & parameters
function printName(first, last){
var intro = "My name is ";
function makeFull(){
return intro + first + " " + last;
}
return makeFull();
}
var d = printName("Paul", "O'Connor");
console.log(d);Couple things to notice:
The
introvariable is used inside of themakeFullfunction.printNamereturns a functionmakeFull.makeFullis not accessible outside of theprintNamefunction.
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
calculateTipin the scope of #1.The function takes in the same two parameters: totalWithoutTip & tipPercentage.
Create a variable in the
calculateTipfunction calledtipAmount.tipAmountwill hold the product of totalWithoutTip & tipPercentage.The
calculateTipinner function returnstipAmount.Set the
totalWithTipvariable equal to the result of runningcalculateTipadded to totalWithoutTip.Return the
totalWithTipvariable.
You can see the answer here.
Last updated