Good morning! Here's our prompt for today.
Understanding Variable Scoping in JavaScript
Let's dig into a fascinating JavaScript example to unravel the mystery of variable scoping.
The Code Snippet
Here's the code we'll be examining:
JAVASCRIPT
1var numOfBeers = 5;
2
3function getMoreBeers() {
4 console.log('I have this many beers: ' + numOfBeers);
5 var numOfBeers = 25;
6 return numOfBeers;
7}
8
9console.log('I now have this many beers: ' + getMoreBeers());
What Do You Expect?
Before running the code, what do you think will be printed to the console? Take a moment to think it over.
Execution Results
Go ahead and execute the code. What do you see?
Your job in the interview is to explain why it runs the way it does.
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
13
var assert = require('assert');
var numOfBeers = 5;
function getMoreBeers() {
console.log('I have this many beers: ' + numOfBeers);
var numOfBeers = 25;
return numOfBeers;
}
console.log('I now have this many beers: ' + getMoreBeers());
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's our guided, illustrated walk-through.
How do I use this guide?