2 years ago
#401
1005hoon
how does memory allocation work in JS when assigning variable with primitive value to a variable?
I've been studying JavaScript language itself, and came up with a question. What does it look like when assinging a variable with primitive value to other variable?
For example, take a look at the code below, and this is what I think happens:
var num = 30;
var newNum = num;
num = 50;
newNum = 50;
Step by step, I believe that in case of primitive values:
Before actually running JavaScript code:
- JavaScript engine checks for variables declared before running code
- then allocates memory for each variables declared
- then puts the variable names for identification purpose
- then initialize with value
undefined
Once JavaScript runs:
- it allocates primitive value
30
to location where its identification isnum
- it copies the primitive value saved at memory from #1, then saves it to other memory location where its identification is
newNum
- then, it allocates new memory space and copies primitive value
50
- and it detaches the variable name
num
from existing memory to new memory space allocated from #3, - It allocates new memory space and copies primitive value
50
- and it detaches the variable name
newNum
from existing memory to new memory space allocated from #5
So far, this is my understanding of how JavaScript allocates its primitive values with var
declaration.
However, I've found some describes differently. They say, both variables num
and newNum
would point to a same memory space where primitive value 30
is located at. Then, once reassignment happens, they would each detach and point to new memory space where primitive value 50
is located at.
javascript
variables
memory
primitive
0 Answers
Your Answer