One Pager Cheat Sheet
- We can observe that the
getMoreBeers()
function overwrites thenumOfBeers
variable, therefore when it is logged25
will be printed out, which can be explained by scope. Executing
this code willprint
theoutput
.- The order of the console log statements is determined by how the
call stack
works, with thegetMoreBeers()
function pushing the original statement onto the stack and executing first. - A call stack is a
data structure
that allows a program to keep track of function calls using thestack
(first in, last out) data structure. - The
variable
is returned as "undefined" in the log despite being clearly defined above the function. - We should
let
/const
and keep track of variable declarations to avoid unexpected results due tohoisting
. - The declarations of variables with the
var
keyword in JavaScript are hoisted, but not the initializations.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
12
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
That's all we've got! Let's move on to the next tutorial.
If you had any problems with this tutorial, check out the main forum thread here.