Outside the Scope of My Last Article

Omar Gonzalez
3 min readApr 11, 2021

JavaScript. My Flatiron School bully, who eventually grew to embrace (or at least tolerate) me. As mentioned in my last article, I had difficulty making the leap from Ruby. One major difference between the two languages, as mentioned in my last article, is the scope of local variables. In both languages a local variable that’s created within a method (or a “function” in JS) will be inaccessible outside of it. And vice versa in Ruby, unless it’s passed to the method as an argument when the method is called; but that’s not the case in JavaScript.

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?

Well, JavaScript is harder-working than Ruby. If at first it doesn’t succeed, it tries, tries again. When a JS function gets called, and the JS engine encounters a variable, the engine scours the local scope, i.e., the scope within the function, hoping to find a value for said variable. In this case the JS engine encounters the name variable, and finds no corresponding value within the local scope. This is when it goes the extra mile by jumping to the scope one level above, in this case the global scope, where it renews its search. And the search bears fruit when it finds the very first line.

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!

--

--