Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

300
Views
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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!