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

357
Visualizações
If strings are immutable in Javascript, why does the += operator work the way it does?

Everything I'm reading about modifying strings in Javascript says that strings are immutable. Hence why concat returns a new string that is a modification of the original:

let originalString = 'hello';
let modifiedString = originalString.concat(' world');
console.log('originalString:', originalString);
console.log('modifiedString:', modifiedString);

results in:

"originalString: hello"

"modifiedString: hello world"

So far it makes sense. The original string remains even after concat because strings are immutable.

However, if I do the following:

let originalString2 = 'hello';
let modifiedString2 = originalString2 += ' world';
console.log('originalString2:', originalString2);
console.log('modifiedString2:', modifiedString2)

the result is:

"originalString2: hello world"

"modifiedString2: hello world"

This sure seems like it's mutating the original string to me. If that is not what's happening, can someone explain it to me? I've even found articles that go over the ways to modify strings that say at the beginning "Javascript strings are immutable" and later go on to say that the += method is mutating the original string, so I'm getting contradictory information.

JSFiddle of the simple test

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think it's because of the short hand addition operator (+=) you're using. It's actually doing 2 operations first addition then assignment.

let x = 2;
x += 2;
// The above line is equivalent to the following.
x = x + 2;

So for you're example

let str = "hello";
str += "world"; // is the same as 
str = str + "world";

So we are making a new string by str + "world" then assigning it to our str variable. So it's still immutable :)

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