Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!