0

I wonder what happens when I try to assign one object to another?

function make(g: any, b: any) {
    g = b;
}


let obj = {id: 1};
let obj2 = {id: 2};

make(obj, obj2);

console.log(obj);
console.log(obj2);

From point of view memory, what happens? As we know value is passed by link for object, it means g will not be changed.

Why this code works different?

function make(g: any) {
    g = {};
}

let obj = {id: 1};
make(obj);
console.log(obj);
  • 6
    *"I wonder what happens"* Just try it? – Reyno Aug 24 '21 at 08:25
  • I mean what happens in memory, not visual –  Aug 24 '21 at 08:29
  • It's the same as `a = {foo: 1}; b = a;` - you assign a new name to an old object. – VLAZ Aug 24 '21 at 08:31
  • 6
    `g` is a reference that points to some memory that stores `obj`. `b` is a reference that points to some memory that stores `obj2`. `make()` overwrites the content of `g` with the content of `b`. `g` and `b` only exist in `make()`. Right now your script is a big no-op. – Andreas Aug 24 '21 at 08:32
  • 2
    https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language – jhylands Aug 24 '21 at 08:48

0 Answers0