Note that code like this will not work with arrays and objects because those features do not use the word “stack” anywhere in their process (in order for them to be used effectively, one would have to understand how their internal structuring alters this concept).
- It can be conceptualized as a stack of objects (which are essentially name/value pairs).
- When we declare a variable using the var keyword, it gets its own link on the stack.
- When we use push() function, it sends a value to the stack and when we call pop() function, it retrieves an item from the top of the memory stack and removes it from there (if there is nothing at its top after iterating through all values with for loop, then its .length property gets set to 0).
Declaring a variable: Consider the following snippet.
var name = “James”;
var age = 35;
The above variable declaration creates two new variables and stores their respective values.
- If you have a larger number of variables then they are stored in the same order as they are declared in the source code.
- Each one is placed on top of the memory stack, one successive layer at a time.
This can be visualized as shown below:
When we declare a variable using the var keyword, its name gets associated with an empty part of the heap which is known as a variable object.
- Concatenating strings: When dealing with data that contains strings, we often use concatenation as one way of pushing data onto the stack (without having to manage memory management manually). This can be done using the ” + ” operator.
- Overflow – main pile and overflow pile: When we use the push() function, it sends a value to the stack.
- It keeps appending values to the top of the heap until there isn’t enough space (i.e., whenever it encounters an empty part in the heap, it marks it as being in use).
- The value that is sent to this “overflow” then goes into another part of the memory heap which is called Off-Main-Pile (OMP). This second memory heap is also known as “overflow” or “spill” area.
The main heap contains variables that have been declared using the var statement, while the other heap contains all other variables.