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

148
Views
Why are JavaScript primitives immutable? This seems inefficient

This is not really a question per se, but I am looking for information on why JavaScript creates a new value whenever something is reassigned.

For example, a for loop:

for(let i = 0; i < 1000; i++)
   console.log(i);

I have researched that all primitives are immutable and reassigning them actually creates a new value in memory, why not overwrite the existing address?

It seems inefficient that a for loop running will create 100 unused locations when it completes when it could have used 1. It seems strange to me, but I am sure there is a valid reason for it?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Reassigning a primitive value to a variable overwrites the value at the address that the variable points to with a copy of the primitive value.

This loop will overwrite the value at the address that the variable i points to 1000 times. It will not allocate 1000 addresses in memory.

for(let i = 0; i < 1000; i++) {console.log(i);}

What is true is that if you assign to a variable a primitive value from another variable the value will be copied and both variables would point to different locations in memory. You can check it:

let a = 10;
let b = a; // the value 10 from a gets copied to b
a = 20; // the value 10 gets overwritten by 20 in a
console.log(b); // prints 10

Edit:

To answer the question directly: saying that js primitive values are immutable is another way of saying that they get assigned by value as opposed to arrays and objects that get assigned by reference (or are mutable).

Whether a new memory allocation happens or not on each assignment of a primitive value to a variable is an implementation detail, but you can trust that it is done in the most efficient way by modern js engines.

about 4 years ago · Juan Pablo Isaza 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!