Revise JavaScript #01
In this part, we’ll explore call stack, memory heap, stack overflow, and garbage collection in JavaScript with simple explanations and examples to strengthen your fundamentals.
CALL STACK AND MEMORY HEAP
The JavaScript engine does a lot of works for us, but 2 of the biggest jobs are reading and executing it. We need a place to store and write our data and a place to keep track line by line of what's executing. That's where the call stack and the memory heap come in.
Memory Heap
The memory heap is a place to store and write information so that we can use our memory appropriately. It is a place to allocate, use and remove memory as needed. Kind of storage room of boxes that are unordered.
// tell the memory heap to allocate memory for a number
const number = 11;
// allocate memory for a string
const string = "some text";
// allocate memory for an object and it's values
const person = {
first: "Brittney",
last: "Postma"
};Call Stack
The call stack keeps track of where we are in the code, so we can run the program in order. Things are placed into the call stack on top and removed as they are finished. It runs in a first in last out mode. Each call stack can point to a location inside the memory heap.
function subtractTwo(num) {
return num - 2;
}
function calculate() {
const sumTotal = 4 + 5;
return subtractTwo(sumTotal);
}
calculate();When the program starts, JavaScript first pushes the Global Execution Context into the call stack. Then calculate() is called and pushed onto the stack, where it calculates sumTotal = 9. Next, subtractTwo(9) is called and added on top of the stack, it returns 7, and then it gets removed. Finally, calculate() returns 7 and is also removed from the stack, leaving only the global context again.
Stack Overflow
If we keep calling function that are nested inside each other, it's called stack overflow.
// When a function calls itself,
// it is called RECURSION
function inception() {
inception();
}
inception();
// returns Uncaught RangeError:
// Maximum call stack size exceededGarbage Collection
Javascript is a garbage collected language. If you allocate memory inside of a function, JS will automatically remove it from the memory heap when the function is done being called. However, we can not forget about memory leaks.
var person = {
first: "Brittney",
last: "Postma"
};
person = "Brittney Postma";In the example above a memory leak is created. By changing the variable person from an object to a string, it leaves the values of first and last in the memory heap and does not remove it. This can be avoided by trying to keep variables out of the global namespace, only instantiate variables inside of functions when possible.
JavaScript is a single threaded language, meaning only one thing can be executed at a time. It only has one call stack and therefore it is a synchronous language.
Category
JavaScript