A Global Catastrophe

Omar Gonzalez
3 min readApr 28, 2021

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.

Variable ruby_x gets created in Ruby; no need for any keyword.
Variable x gets declared in JavaScript with no keyword.

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.

Variable ruby_y gets created within a method.
Variable y gets declared within a JavaScript function and without the benefit of var, let or const.

But let’s take a look at the SCOPE of variables y and ruby_y.

Declared inside the method, variable ruby_y is undefined outside of it.

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…

The scope of variable y exceeds the confines of the function within which it was declared.

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!

--

--