First of all, this story is based on Stephen Curtis -33 Fundamentals Every Javascript Developer Should Know and you can read it here.
I thought it is great concepts to know although it is not a requirement. So i decided to learn and explain these concepts one by one.
#1. Call stack
What we are gonna learn today is Call stack.
JavaScript is a single-threaded programming language, which means it has a single Call Stack. Therefore it can do one thing at a time.
Let’s see the example below.
function first(){
// [1]
second()
// [2]
}function second(){
// [3]
console.log('I love medium')
}first();
The code above would be executed like this:
Call stack list: empty
- Ignore all functions, until
first()
function is invoked. first()
function is invoked.- Add the
first()
function to the call stack list.
Call stack list:
first()
3. Execute [1]
inside of first()
function.
4. second()
function is invoked.
5. Add the second()
function to the top of call stack list.
Call stack list:
second()
first()
6. Execute [3]
inside of second()
function.
7. “I love medium” is logged on the console .
8. Remove second()
function from the call stack list.
Call stack list:
first()
8. Execute [2]
inside of first()
function.
9. Remove first() function
from the call stack list.
Call stack list: empty
We start with an empty Call stack. Whenever we invoke a function, it is automatically added to the Call stack. Once all lines of code inside of a function is executed, it is removed from the Call stack.
You can see stack traces are being constructed when an exception is being thrown. Take a look at the code below
function first() {
second();
}function second() {
third();
}function third() {
throw new Error('error');
}first();
Assume that this code is executed by app.js
The error message says that error happened at third()
which is executed by second()
which is executed by first()
which is executed by app.js
It shows you call stack list when error happened.
Conclusion
Javascript interpreter write down the todo list to execute all lines of your code.
Higher priority is written on the top.
Execute their plan one by one from the top and remove when it is done.
reference :
How JavaScript works:an overview of the engine, the runtime, and the call stack — Alexander Zlatkov
MDN