Today I Learned

hashrocket A Hashrocket project

Variable Hoisting in JavaScript

I while back I wrote about variable hoisting in Ruby. This is when the value of a variable is 'hoisted' to the top of its scope with value nil, rather than left undefined, even if that variable is protected from ever being declared by (for example) an always-false conditional.

Today I learned that JavaScript shares this behavior.

Here's an example. Let's declare two global variables:

$ validGlobal = 'we need this';
=> "we need this"
$ questionableGlobal = 'aggressively scoped';
=> "aggressively scoped"

Then, make a function that declares a local variable with the same name as one of our globals:

$ var example = function() {
  console.log(validGlobal);
  console.log(questionableGlobal);

  var questionableGlobal = 'uh oh';

  console.log(questionableGlobal);
}();

=> "we need this"
=> undefined
=> "uh oh"

validGlobal logs its global value, as expected. But because questionableGlobal is also declared as a local variable in this scope, when we try to log it before that declaration occurs, it returns undefined, rather than the global value. This is to protect us from raising a ReferenceErrorquestionableGlobal has been 'hoisted' like a pirate flag.

This is a noteworthy feature of both Ruby and JavaScript.

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.