1

I've noticed things like this work:

let x = { a: 1 };
function reassignProperty(obj, key, newValue) {
  obj[key] = newValue;
}
reassignProperty(x, "a", "hello");
console.log(x.a); //prints hello

But this doesn't:

function reassignObject(obj) {
    obj = { a: "some new value" };
}
reassignObject(x);
console.log(x.a); //still prints hello

It seems you can reassign properties of an object (pointers within an object), even if the values are reference types themselves. i.e. we could do things like reassignProperty(x, "a", { inner: 55 }), and it will still be the same outside the function scope. But reassigning the reference to the object itself doesn't?

I've seen people argue javascript passes variables into functions by value, but not by reference. Why then does it seem to able to reassign the properties inside the object, and have access to the changes outside the function scope? This doesn't seem to me to be strictly "pass by value"

Jackson Lenhart
  • 630
  • 3
  • 7
  • 19
  • 1
    In javascript, all variables are always `passed-by-value` look here https://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value – CodeLover Feb 20 '18 at 04:52
  • 1
    in javascript objects are called-by-sharing. if you modify the internal structure of object then it will change the original parameter also. But it you re-assign it then original parameter will be intact. – Lalit Feb 20 '18 at 04:54
  • 1
    JavaScript _passes references by value_. It doesn't _pass by reference_. That's why you're able to change an object's properties inside a function and have the change reflected outside the function. – JLRishe Feb 20 '18 at 04:54

1 Answers1

0

In the second case use dot notation instead of object literal

let x = {
  a: 1
};

function reassignObject(obj) {
  console.log("Passed from function call ", obj);
  if (obj.hasOwnProperty('a')) {
    obj.a = "some new value"
  }
  console.log("After reassinging value ", obj)

}
reassignObject(x);
console.log(x.a);
brk
  • 48,835
  • 10
  • 56
  • 78