2 years ago

#401

test-img

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:

  1. JavaScript engine checks for variables declared before running code
  2. then allocates memory for each variables declared
  3. then puts the variable names for identification purpose
  4. then initialize with value undefined

Once JavaScript runs:

  1. it allocates primitive value 30 to location where its identification is num
  2. it copies the primitive value saved at memory from #1, then saves it to other memory location where its identification is newNum
  3. then, it allocates new memory space and copies primitive value 50
  4. and it detaches the variable name num from existing memory to new memory space allocated from #3,
  5. It allocates new memory space and copies primitive value 50
  6. 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

Accepted video resources