A Global Catastrophe
In my more recent articles, I’ve compared and contrasted the rules that govern variables in Ruby with the corresponding JavaScript mechanics. In particular, I’ve examined the three JS keywords with which variables are declared: var, let and const. But there’s a fourth way to skin that particular cat; just as in Ruby, a variable in JavaScript may be declared with no keyword at all.
No var; no let; no const. That can be done outside of any Ruby method or JS function, as seen above, or it can be done within such confines.
But let’s take a look at the SCOPE of variables y and ruby_y.
In Ruby, the variable becomes a non-entity the moment it tries to spread its wings beyond the nest of the method. In JavaScript, though…
No handy error message. In fact, no error at all; at least not the type of error that we’ll spot right away. Remember Outside the Scope of this Article? I pointed out that any variable declared within a JavaScript function will be function-scoped even if the declaration takes place deeper than the parameters of the function, such as inside of an if block. Well, a JS variable declared with no keyword will be scoped even wider than that.
The scope of such a variable is global, whether the programmer intends it or not. Forgetting to declare it with a keyword; a perfectly innocent mistake, especially for someone trying to transition over to JS from Ruby… not that I ever have… because I HAVEN’T!