The Runtime Environment
- The JavaScript engine
- Web API's
- Job Queue
- Callback Queue
- Event Loop
The JavaScript engine
- Memory Heap
- This temporarily holds data.
- Assigning variables, functions, etc are automatically stored in the Memory Heap.
- The JS engine will remove most items from memory when they are no longer used. This is one of the reasons Global variables are often a bad idea as these will not be removed from memory.
- Call Stack - orders and executes code.
The Call Stack & Synchronous Processing
Code is executed synchronously, meaning that commands are processed one at a time on the Call Stack. As the JavaScript code is processed, operations that need to be performed are stacked one on top of the other. These operations run from the top down, meaning the last one placed runs first, then the one beneath it, and so on. NOTE: Stack overflow occurs when commands keep being placed on top of the stack to the point where there are no more spots left. This prevents the stack from executing and can trigger an error in the browser or, especially in older browsers, cause it to crash.function functOne() {
functTwo();
return console.log('The First Function');
}
function functTwo() {
functThree();
return console.log('The Second Function');
}
function functThree() {
console.log('The Third Function');
}
functOne();
// At runtime, these get added to the Call Stack
// The Call Stack would look like this and run the top function first: functThree() functTwo() functOne()
// The output would be console.log('The Third Function'); console.log('The Second Function'); console.log('The First Function ');
Asynchronous JavaScript - Utilizing Web API's, Job Queue, Callback Queue and the Event Loop
While the Call Stack is processed synchronously, the greater JavaScript runtime environment works asynchronously, meaning multiple steps at one time. This allows for items that are not ready to be processed on the Call Stack, to be set aside until a later time and then run, resolved and made ready to be placed on the Call Stack once it is empty.
The
The
The