0

is this expected?

const testObj = {
  a: 'hi',
  b: 'there'
}


function destructured_test({a, b}) {
    a = 'bye';
}

console.log(testObj);
destructured_test(testObj);
console.log(testObj);

function test(t) {
    t.a = 'bye';
}

console.log(testObj);
test(testObj);
console.log(testObj);

only the function 'test' mutates testObj 'destructured_test' seems to be copying the properties over instead of preserving the reference

bturner1273
  • 660
  • 7
  • 18
  • That's how values work. [Why should this work different than your `destructured_test`](https://jsbin.com/pivameb/1/edit?js,console)? See also: [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/q/518000) – VLAZ Mar 17 '22 at 19:16
  • hmm now I wonder if a and b were objects if they would be passed by reference – bturner1273 Mar 17 '22 at 19:19
  • JS is *always* pass by value. – VLAZ Mar 17 '22 at 19:20
  • meh passing a pointer by value is kinda like passing an obj by reference no? that is what it is doing for 'test' function – bturner1273 Mar 17 '22 at 19:21
  • but then it goes and makes copies for the destructure, seems wonky – bturner1273 Mar 17 '22 at 19:22
  • The value of an object is its reference. So, `f(obj)` is still passing a value. However, inside that function you cannot have `arg = {new: "object"}` and have that take effect on the passed in parameter. Because you're not manipulating the reference there. – VLAZ Mar 17 '22 at 19:23
  • if a and b were objects then any changes you did to them in destructured_test would be visible in console.log(testObj). – James Mar 17 '22 at 19:24
  • @James only if changing properties. `a = "hello"` wouldn't do anything outside the function. – VLAZ Mar 17 '22 at 19:25
  • Yes, sorry, I meant if you added a property to object a or pushed an element into an array b, it would be reflected, but completely redefining a and b would just result in new values for a and b and not do anything to testObj. – James Mar 17 '22 at 19:26
  • 1
    When you destructure function arguments with `foo({ a }) { bar(a) }` This is similar to `foo(_ref) { var a = _ref.a; bar(a) }` You can check such things by transpiling to ES2015. – Wyck Mar 17 '22 at 19:54

0 Answers0