#You dont know js lexical scope code
Secondly, the computer will invoke the writeName() function (which is the only code in the sayName() function).Īt this point, since the code in writeName() instructs the computer to call and return the fullName variable's content, the computer will call fullName. In the snippet above, whenever the profile() function gets invoked, the computer will first invoke the sayName() function (which is the only code in the profile() function). JavaScript's scope chain determines the hierarchy of places the computer must go through - one after the other - to find the lexical scope (origin) of the specific variable that got called.įor instance, consider the code below: // Define a variable in the global scope: Note: The global scope is the last link in JavaScript's scope chain. In other words, there are four (4) spaces from fullName’s invocation scope to its lexical scope (the global scope in this instance). WriteName() scope -> sayName() scope -> profile() scope -> global scope Therefore, the scope chain that exists from the variable’s call to the global scope is: In the snippet above, observe that the fullName variable got called from the writeName() function's scope. What is a Scope Chain?Ī scope chain refers to the unique spaces that exist from the scope where a variable got called to the global scope. Instead, it must sequentially go through the scope chain to look for fullName. Keep in mind that whenever the writeName() function gets invoked, the computer will not go straight to the global scope to call the fullName variable. In other words, writeName() is locally visible and accessible only to code in the sayName() function.
This means that it is visible and accessible globally to all code within the script.īut we defined writeName() within the sayName() function, so it is locally scoped to sayName(). In the snippet above, we defined the fullName variable in the global scope. Here's an example: // Define a variable in the global scope: