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

121
Visualizações
Affects of object assignment within a function on global object values

Can someone please help explain why the value property of obj1 remains the same while in obj2 it changes? I know it has to do with obj1 being assigned to obj2 within the change function but I'm not exactly sure why. Thanks!

let obj1 = {
  value: "a"
}

let obj2 = {
  value: "b"
}


function change(obj1, obj2) {
  obj1 = obj2
  obj1.value = "c"
}

change(obj1, obj2);


console.log("obj1: ", obj1, "obj2: ",obj2);

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

0

Let's rename some variables so you can see what's going on

let obj1 = {
  value: "a"
}

let obj2 = {
  value: "b"
}


function change(param1, param2) {
  param1 = param2
  param1.value = "c"
}

change(obj1, obj2);


console.log("obj1: ", obj1, "obj2: ",obj2);

Now as you can see, obj1 is never changed. What you are changing is parameter of change function that is named the same as variable from outer scope.

about 4 years ago · Juan Pablo Isaza Relatório

0

This is because variables of objects are actually pointers to the object. That's why when they are passed to a function, any changes of the pointer properties would change the actual object. Whereas, if you simply assign a value to a variable of type object, then the pointer itself is changed, not the object.

So obj1 = obj2 sets the obj1 pointer to be obj2 pointer. Now, if obj1.value = "c" then a property of the object obj1 (which is now obj2) will change, affecting the original object.

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