1

Hi I have a question about this code, why does it prints "Wild" instead of "Tabby"

var cat = { name: "Athena" };

function swap(feline) {
    feline.name = "Wild";
    feline = { name: "Tabby" };
}
swap(cat);
console.log(cat.name);
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 2
    From the marked duplicate: *Specifically, when you pass an object (or array) you are (invisibly) passing a reference to that object, **and it is possible to modify the contents of that object, but if you attempt to overwrite the reference it will not affect the copy of the reference held by the caller*** – 0stone0 May 12 '22 at 11:39

1 Answers1

2

feline as an identifier is a local variable for your function. At the beginning it refers to cat from outside, and thus changing a part of the object is visible outside.

However when you set feline to a brand new object, that happens locally.

var cat = { name: "Athena" };

function swap(feline) {
    console.log("feline, cat:",feline.name,cat.name,"feline===cat:",feline===cat);
    feline.name = "Wild";
    console.log("feline, cat:",feline.name,cat.name,"feline===cat:",feline===cat);
    feline = { name: "Tabby" };
    console.log("feline, cat:",feline.name,cat.name,"feline===cat:",feline===cat);
}
swap(cat);
console.log("cat:",cat.name);
tevemadar
  • 12,389
  • 3
  • 21
  • 49