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?
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.