Mark As Completed Discussion

Analyzing Output in JavaScript: The Case of Mysterious Beers

The Code and Its Output

Let's look at the JavaScript code snippet and its output when executed:

JAVASCRIPT
1var numOfBeers = 5;
2
3function getMoreBeers() {
4  console.log('I have this many beers: ' + numOfBeers);
5
6  var numOfBeers = 25;
7  return numOfBeers;
8}
9
10console.log('I now have this many beers: ' + getMoreBeers());
11
12// Output
13// I have this many beers: undefined
14// I now have this many beers: 25

Your Initial Guess vs Reality

Upon a first look, you might expect the output to show the number of beers as 5 and then 25. However, the output is quite different. Let's explore why.

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