Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda