Home > Software engineering >  Javascript Object property value when reassign the object
Javascript Object property value when reassign the object

Time:10-23

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related