Mark As Completed Discussion

The Output Mystery

You've noticed that the output is intriguing. Despite having the variable numOfBeers defined before the function, the console log within the function prints it as undefined.

JAVASCRIPT
1// Output
2// I have this many beers: undefined
3// I now have this many beers: 25

The Role of Scoping and Hoisting

This oddity has to do with two core JavaScript concepts: scoping and hoisting.

  1. Local vs Global Scope: Even though a variable with the same name exists in the global scope, JavaScript gives priority to the local scope within a function.

    JAVASCRIPT
    1var numOfBeers = 5;  // Global Scope
  2. Hoisting in Action: In JavaScript, all variable declarations are "hoisted" to the top of their scope. This means that as soon as the function getMoreBeers() begins execution, JavaScript hoists the variable numOfBeers to the top of the function, but it remains uninitialized.

    JAVASCRIPT
    1function getMoreBeers() {
    2  console.log('I have this many beers: ' + numOfBeers);  // Local Scope, Hoisted but uninitialized
    3  var numOfBeers = 25;  // Local Scope, Initialized
    4  return numOfBeers;
    5}
  3. The Undefined Log: When the console.log statement within getMoreBeers() runs, it finds the local, hoisted, but uninitialized numOfBeers and prints it as undefined.

    JAVASCRIPT
    1console.log('I have this many beers: ' + numOfBeers);  // Output: undefined