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.
1// Output
2// I have this many beers: undefined
3// I now have this many beers: 25The Role of Scoping and Hoisting
This oddity has to do with two core JavaScript concepts: scoping and hoisting.
- 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
- 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- numOfBeersto 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}
- The Undefined Log: When the - console.logstatement within- getMoreBeers()runs, it finds the local, hoisted, but uninitialized- numOfBeersand prints it as- undefined.JAVASCRIPT- 1console.log('I have this many beers: ' + numOfBeers); // Output: undefined