Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

113
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda