Created
March 8, 2019 11:10
-
-
Save safebear/c35479db9a260eaee878f5f5de6d03e6 to your computer and use it in GitHub Desktop.
Closures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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