Outside the Scope of this Article
Let’s look at the JS counterpart of a Ruby function that I built and examined last week.
As in last week’s example, the name variable is created in the first line, outside of the function. And no variable at all is assigned any value or even declared within the function. But when the function is called, there is no “undefined local variable… ‘name’” error. Instead, we see, as intended, “That Omar is a great guy.” Why?
Because the JS engine is willing and able to conduct its searches in this concentrically circular manner, it’s quite feasible to embed a function within a function within a function, and so on, without needing to declare a variable or assign it a value within each level of scope, such as in the following example.
The firstName variable is successfully invoked within the scope of the likeJamesBond sub-function, but is assigned a value only outside of that scope, within the scope of the omarIntroducesHimself function, which is the function that gets explicitly called and yields the intended result:
“My name is Gonzalez; Omar Gonzalez.” Thank you so much for having read this article, multiple scopes and all!