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);
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);
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);