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

136
Views
Do two or more identical primitive values in JS share the same memory location?

Let's imagine we have the following piece of code:

let a = 10;
let b = 10
printNumber(10)

function printNumber(num){
   console.log(num)
}

Will primitive values 10, that are assigned to variables a and b and also passed as an argument to the function printNumber, share the same memory location? Will it be effectively just one primitive value 10 stored in memory that can be used in source code unlimited times without the need to bloat the memory?

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

No, variables a and b do not share same memory location. Each variable is stored in a stack. So they convey the same value but not same reference.

But, of course, value 10, in it of itself, is accessed by JavaScript through a specific memory location, which JavaScript knows.

about 4 years ago · Santiago Gelvez Report

0

(Disclaimer: I hope i understood the question correctly)

In your example, you are creating two independent variables a, b with the same value 10 - they are assigned during JIT-compilation, so effectively you get 2 memory locations with variables a, b coincidentally holding the same value. The original number itself is not part of the JIT compiled code. Aside from that, you are creating a function (printNumber) with a parameter (num) that will be filled during JIT-compilation with the number (again, 10) when invoking the function ('passing the argument'). The parameter is then locally scoped inside the function, and the memory allocated will be garbage-collected after leaving the function. So, the memory footprint of your JS program is not defined by the use of constants (your primitive values) but instead by the number of variables you declare (and a lot of other things, of course).

To make it a bit more clearer - i added some output to your program along with some variable mutations.

let a = 10
let b = 10
console.log('a init',a)
console.log('b init',b)
printNumber(10)
printNumber(a)
printNumber(b)
function printNumber(num){
   
   console.log('printNumber - num',num)
   console.log('printNumber - a',a)
   a++;
   num++;
}
console.log('a exit',a)
console.log('b exit',b)

about 4 years ago · Santiago Gelvez Report
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!