0

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'}

3
  • This might helpful to you Is JavaScript a pass-by-reference or pass-by-value language? Commented Oct 22, 2022 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. Commented Oct 22, 2022 at 12:34
  • read this Commented Oct 22, 2022 at 12:40

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.