-1

var cat = { name: 'Athena' };

function swap(feline) {
  feline.name = 'Wild';
  feline = { name: 'Tabby' };
}

swap(cat);
console.log(cat.name);
Can Anyone explain why cat.name showing "Wild" because I've again assigned the feline = {name:'Tabby'}
flyingfox
  • 13,414
  • 3
  • 24
  • 39
  • This might helpful to you [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language#:~:text=JavaScript%20always%20evaluates%20each%20expression,by%20reference%22%20language%2C%20however.) – flyingfox Oct 22 '22 at 12:15
  • In the first line, feline was just a reference to cat. Since objects are passed by reference changing feline updates cat. On the second line, you are reassigning the feline object with another object. This doesn't update the original cat object. – 31piy Oct 22 '22 at 12:34
  • [read this](https://stackoverflow.com/a/50530975/12146581) – Mohamad Ghaith Alzin Oct 22 '22 at 12:40

2 Answers2

1

in here you have two variables

  1. cat
  2. feline

so when you are passing the cat to swap function, actually you passing reference to cat variable, that is address of cat variable. because of this feline will point to original object of cat. so when you change feline.name, you are actually changing cat

then you are assigning another variable that is
feline = { name: 'Tabby' }; by doing this now feline variable is no longer pointing to same cat object, so cat object which have name 'wild' will be logged

1

When you pass cat as a parameter to the swap function, you are giving the reference to the cat variable. So now feline points to the same reference as cat. Both are looking at the same object through reference.

feline.name = 'Wild'

feline changes the name of the object it is referencing. Since the variable cat also looks at the object in this reference, it will display 'Wild' when it reaches the name via cat.

feline = { name: 'Tabby' }

Where you assign a new object, a new reference to the feline variable. So it no longer looks at the reference the cat variable is looking at. In short, cat is unaffected.

I tried to summarize very briefly without going into details.

kanvil
  • 326
  • 2
  • 6