Hoisting and Call Stack (Hard)
Good afternoon! Here's our prompt for today.
You may see this problem at Autodesk, Apple, Paypal, Reddit, Jane Street, Nvidia, Visa, Walmart Labs, Tanium, Squarespace, Weave, Amplitude, Veeva Systems, At T, Nasdaq, Zuora, and Smartsheet.
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.
xxxxxxxxxx13
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
Results will appear here.