Let's take a look at a live example in code, and use Chrome dev tools to inspect the call stack in real time. So what I have here is a very basic index.html file, and in the script tag, I'm passing a main.js file. Main.js file is where we'll write out code. Let's have a result variable and set it equal to its function first, and we pass in 8.
Let's go ahead and define this function first. The function will take an argument x, and return another function called second, and multiply that argument by 2. Then the function second will take the argument you passed in, and return another function third that will take the argument that you passed on, and will add 16, and this function third will take the argument that you passed in, and now third will return whatever you passed in times 3.
So let's go ahead and actually throw a debugger in here, so we can walk through the program and also console.log the results so we can see it in the console. All right, let's go ahead and move to our browser.
I've already gone ahead and pulled it up in my browser, so I'm going to go ahead and open Chrome dev tools. We're going to start with our sources tab, and what we're going to do is walk through this program function-by-function as it gets executed, and we'll also be watching the call stack.
When I refresh the page it will start with the debugger, and these are all just function declarations, so nothing gets actually executed until we come to this line here, and first gets executed. So watch what happens. All right, when we step into first, first gets put on the call stack. Now, because first returns another function second, watch what happens -- second gets put on the call stack.
Now second returns another function third, so third gets put on the call stack. All right, so neither of these have returned, so they're all on the call stack still.
But watch what happens when third returns. All right, third gets popped off the call stack, and since third returned, second can return. So second gets put off the call stack, and now first can finally return and so first comes off the call stack.
Now our call stack is empty, and if we play this and go to our console, we'll see 96, which is exactly what we expected.