The Runtime Environment
There are four components of the JavaScript runtime environment:
- The JavaScript engine
- Web API's
- Job Queue
- Callback Queue
- Event Loop
The JavaScript engine
The two components of the JS engine are:
- 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 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, or one at a time, on the Call Stack. As the JS code is processed, operations that need to be performed are stacked one on top of the other. These operations then run from the top down meaning the last one placed runs first, then the one under that and so on.
NOTE: Stack overflow is what it is called when commands keep getting placed on top of the stack to the point where there are no more spots left. This prevents the stack from being executed and will trigger an error in the browser or, especially in older browsers, can 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
One Reply to “How JavaScript Works”