Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Closures
function sayHi(greeting){
console.log(greeting)
}
sayHi("hello")
// 'greeting' variable contains the word 'Hello' when 'sayHi' is run
// but the 'greeting' variable no longer exists anywhere after 'sayHi' has finished executing
console.log(sayHi.greeting)
console.log(greeting)
// it's been garbage collected. now let's add a return function
function sayHi(greeting){
return function (name) { console.log(greeting + ' ' + name)}
}
// This leads to some unusual syntax
sayHi("Hello")("John")
// Now lets store our returned function in a variable
var nameFunction = sayHi("Hello")
// And then run it
nameFunction("John")
// It should print 'undefined John'
// This still prints 'Hello John' even though the 'greeting' variable that contains the word 'Hello' should no longer exist!
// Closures also cause unusual behaviour:
// Let's fill up an array with numbers:
var arr = []
for (var i = 0; i < 3; i++) {
arr.push(i)
}
console.log(arr[0])
console.log(arr[1])
console.log(arr[2])
// Now let's add the 'console.log' into the loop by adding a function.
var arr = []
for (var i = 0; i < 3; i++) {
arr.push(function() {
console.log(i)
})
}
arr[0]() // = 3!
arr[1]() // = 3!
arr[2]() // = 3!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.