2

In the following code

a = 1
b = {"a": a} // this output {"a": 1}
a = 2
console.log(b) // this still output {"a": 1}

In such situation, will the memory which store the content 1 be free when reassign the variable to 2?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
kongkongyzt
  • 190
  • 1
  • 10
  • 1
    No, because the `1` is still available, as you can see in `b`. If it went away, the `b` object would break. See https://stackoverflow.com/questions/54173974/what-are-the-result-of-the-mark-and-sweep-in-that-code#comment95176931_54173974 for a similar question – CertainPerformance Jan 16 '19 at 01:35
  • Check this out as well: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management#Garbage_collection – Dacre Denny Jan 16 '19 at 01:39
  • `a` is a primitive. It's not just a reference to memory, it is a `double` _by value_. Its _value_ is _copied_ to the property `b.a`. – Patrick Roberts Jan 16 '19 at 01:58

2 Answers2

2

variable did not lose its memory space until it destroyed.

when you write

  a = 1
  b = {"a": a}        

value of a is assigned to a node of object b. a variable is not bind to a node. if you want to update node a to new value you can do by:

  b.a = 2;        
  console.log(b.a); //will print 2        
Mudassir
  • 578
  • 4
  • 6
0
b = {"a": a} // this output {"a": 1}

this instruction tells the compiler to create a new object and set the key "a" to the same value the variable a has right now, so the value 1 is copied into the memory of b.