Read 10 - corey-marchand/data-structures-and-algorithms GitHub Wiki

A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function, etc.

When a script calls a function, the interpreter adds it to the call stack and then starts carrying out the function. Any functions that are called by that function are added to the call stack further up, and run where their calls are reached. When the current function is finished, the interpreter takes it off the stack and resumes execution where it left off in the last code listing. If the stack takes up more space than it had assigned to it, it results in a "stack overflow" error.

LIFO: When we say that the call stack, operates by the data structure principle of Last In, First Out, it means that the last function that gets pushed into the stack is the first to be pop out, when the function returns.

Let us take a look at a code sample to demonstrate LIFO by printing a stack trace error to the console.

function firstFunction(){throw new Error('Stack Trace Error');} function secondFunction(){firstFunction();} function thirdFunction(){secondFunction();} thirdFunction(); When the code is run, we get an error. A stack is printed showing how the functions are stack on top each other. Take a look at the diagram.

Manage function invocation (call): The call stack maintains a record of the position of each stack frame. It knows the next function to be executed (and will remove it after execution). This is what makes code execution in JavaScript synchronous.

Think of yourself standing on a queue, in a grocery store cash point. You can only be attended to after the person in front of you have been attended to. That’s synchronous.

This is what we mean by “manage function invocation”.

How does the call stack handle function calls? We will answer this question by looking at a sample code of a function that calls another function. Here is the example code:

function firstFunction(){ console.log("Hello from firstFunction");} function secondFunction(){ firstFunction(); console.log("The end from secondFunction");} secondFunction();

Types of error messages The first thing that indicates you that something is wrong with your code is the (in)famous error message that the one we saw just moments ago, it usually appears on your console (being developer tools of the browser, terminal or whatever else you are using). For those already used to programming, reading an error message is like second nature, for everybody else, is something you learn either you like it or not so might as well talk a bit about each of them.