Last active
January 15, 2017 04:38
-
-
Save iShafayet/981a8d540d172bef7352c9ce7cbafdb2 to your computer and use it in GitHub Desktop.
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
## The Problem | |
value = 'external' | |
console.log 1, value # 'external' | |
(someFunction = => | |
console.log 2, value # 'external' | |
value = 'internal' | |
console.log 3, value # 'internal' | |
)() | |
console.log 4, value # 'internal' | |
# In the code above, the last console log outputs 'internal' | |
# which indicates that the code inside someFunction has mutated | |
# the value in the external scope. | |
# this is because of how lexical scoping is controlled by the | |
# "sameness" of names across scopes | |
## Solution 1 | |
value = 'external' | |
console.log 1, value # 'external' | |
do (value)=> | |
console.log 2, value # 'external' | |
value = 'internal' | |
console.log 3, value # 'internal' | |
console.log 4, value # 'external' | |
# In this solution, the 'value' variable will retain the external value | |
# when being passed to the new scope. But the value is 'copied' and not | |
# lexically bound in the previous scenario. | |
## Solution 2 | |
value = 'external' | |
console.log 1, value # 'external' | |
((value)=> | |
console.log 2, value # undefined | |
value = 'internal' | |
console.log 3, value # 'internal' | |
)() | |
console.log 4, value # 'external' | |
# In this solution, the 'value' variable in the inner scope | |
# simply has no connection with the one in the outter scope. | |
# the variable in the inner scope in this case is simply | |
# assigned to undefined (as no value is passed when calling | |
# the immediately invoked function | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment