Mark As Completed Discussion

Global Variable: A Common Misconception

Note that var numOfBeers = 5; is a globally defined variable. Intuitively, one might think that this global variable should be accessible within the getMoreBeers function.

JAVASCRIPT
1var numOfBeers = 5;  // Globally Defined Variable

Hoisting: The Culprit

However, this expectation is thwarted by hoisting. Recall that hoisting moves variable declarations to the top of their current scope during the compilation phase.

Global Variable

var vs const and let

The hoisting behavior is specific to the var keyword, making it distinct from const and let. During the lexical analysis step by JavaScript engines, the var numOfBeers inside getMoreBeers is hoisted to the top of the function's scope, even before the function executes.

JAVASCRIPT
1function getMoreBeers() {
2  // Hoisted but uninitialized
3  var numOfBeers;
4  console.log('I have this many beers: ' + numOfBeers);  // Output: undefined
5  numOfBeers = 25;  // Initialization
6  return numOfBeers;
7}

Breaking it Down: What Really Happens

So, when getMoreBeers runs, JavaScript's hoisting places a new var numOfBeers; at the top of the function, without initializing it. This local variable shadows the global one, and since it's uninitialized, the log statement shows undefined.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment