Home > Blockchain >  Value of object property not changed as expected
Value of object property not changed as expected

Time:10-25

I just wanted to know why in my code I have changed cr = 6 in a method, but when printing the original obj cr value, it is not changed to 6, but remains its original value. Why? If instead I use cr.next = 6, then the value gets changed in the original obj. I expect obj.next = 6. The output generated is:

{
  val: 1,
  next: {
    val: 2,
    next: {
      val: 3,
      next: null
    }
  }
} 

I expected the output to be like this:

{
  val: 1, 
  next: 6
}

let obj = {
  val: 1,
  next: {
    val: 2,
    next: {
      val: 3,
      next: null
    }
  }
}

cr = obj.next;
cr = 6;
console.log(obj)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The first part,

cr = obj.next;

Means "The value of the identifier (the word cr) is the value at the location of memory that the object obj.next is"

cr = 6;

Means "Completely disregard any previous value of cr; the value of the identifier cr is now the integer literal 6"


JavaScript, unlike C/C (with pointers, or pass-by-reference vs pass-by-value), does not have a way to change the value of an object with a single identifier (variable name). It can change what the value of the variable is, but not the object it was previously pointing to.

CodePudding user response:

let obj = {
  val: 1,
  next: {
    val: 2,
    next: {
      val: 3,
      next: null
    }
  }
}

cr = obj.next;
cr = 6;

console.log(obj)
console.log("...........................")
obj.next = 6
console.log(obj)
console.log("...........................")
console.log(cr)

cr = obj.next;
cr = 6;
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

When you do cr = obj.next, it makes a new variable and assigns the obj.next value to cr. After that, you assign 6 to cr so it overwrites the current value of cr and there will be only 6.

If you want an answer like {val: 1, next: 6}, you should write obj.next = 6 so you get your desire output.

I hope it helps you "keep coding".

  • Related