Closure and Hoisting
Standard -
Describe how key parts of JS work
- Describe closures
- Describe how hoisting works
Review Lexical Scope
var leftEarly;
var broughtChips;
var invitedTooManyFriends;
var hadTooMuchFun;
function party(personOne, personTwo, personThree) {
leftEarly = personOne
broughtChips = personTwo
invitedTooManyFriends = personThree
var randomPerson = Math.floor(Math.random() * 3);
var hadTooMuchFun = arguments[randomPerson];
}
party("Berto", "CJ", "Danny", "Kyle")
console.log("Left Early: ", leftEarly);
console.log("BroughtChips: ", broughtChips);
console.log("Invited Too Many Friends: ", invitedTooManyFriends);
console.log("Had Too Much Fun: ", hadTooMuchFun);
What happens when we run this?
hadTooMuchFun is undefined because it was never assigned a value
The other variables had values assigned through lexical scope
Hoisting
var berto = "He is a great guy"
makeBertoFunny()
trashTalkBerto()
console.log(berto)
function makeBertoFunny () {
berto += " and he is super funny!"
}
var trashTalkBerto = function () {
berto = "He is stupid and boring"
}
What happens when we run this?
TypeError!!
var berto = "He is a great guy"
makeBertoFunny()
trashTalkBerto()
console.log(berto)
function makeBertoFunny () {
berto += " and he is super funny!"
}
var trashTalkBerto = function () {
berto = "He is stupid and boring"
}
`trashTalkBerto` is undefined when it is invoked because it doesn't get hoisted like `makeBertoFunny`
Closures
Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope).
In other words, these functions 'remember' the environment in which they were created.
Great for interview questions:
function writeInJournal() {
var message = "I love alpacas"
return readJournal
function readJournal() {
return "Roberto's journal says: " + message
}
}
var read = writeInJournal();
var secret = read()
console.log(secret);
Closure and Hoisting
By Roberto Ortega
Closure and Hoisting
- 339