{"id":8426,"date":"2018-12-23T10:38:07","date_gmt":"2018-12-23T15:38:07","guid":{"rendered":"https:\/\/www.carnaghan.com\/?p=8426"},"modified":"2021-03-06T15:49:22","modified_gmt":"2021-03-06T20:49:22","slug":"javascript-call-stack","status":"publish","type":"post","link":"https:\/\/www.carnaghan.com\/javascript-call-stack\/","title":{"rendered":"JavaScript Call Stack"},"content":{"rendered":"\n
In earlier lessons, we wrote code without using any functions. Now that you have been introduced to the various ways we can organize our code within function declarations and expressions, it is helpful to step back for a moment to understand the flow of execution within our code. JavaScript uses a call stack to in order to manage this flow, which is essentially a data structure (or to-do list) that keeps track of function calls using a Last In First Out (LIFO) ordering system. Let’s take a look at an example to help explain this concept.<\/p>\n\n\n\n
\/\/ Call stack example\n\nfunction first () {\n console.log(\"running first\");\n second();\n console.log(\"finished\");\n}\n\nfunction second() {\n console.log(\"running second\");\n}\n\nfirst();<\/code><\/pre>\n\n\n\nIn the code above we have defined two different functions, First and Second. The First function will initiate a console.log and then call Second. Second will in turn execute another console.log and return to control to First. First will execute a third console.log and then return control to main. This is better illustrated in the following steps:<\/p>\n\n\n\n
- in main call stack \/ not in function<\/li>
- in first (executes console.log)<\/li>
- in second (executes console.log)<\/li>
- in first (executes console.log)<\/li>
- in main call stack \/ not in function<\/li><\/ol>\n\n\n\n
The diagram below illustrates the five different states of the call stack during execution of the program above. Visually you can see how the principle of Last In First Out (LIFO) is followed within the call stack. It is important to gain an understanding of your program flow within the JavaScript call stack in order to manage your functions and overall organization of code.<\/p>\n\n\n\n