0

Lets say I have a function

function person(){
   var dog = new pet();
}

var kevin = new person();
kevin = new person();

What happens to the first person that was assigned to kevin?
Do i have to delete it manually or will javascript delete the unreferenced person. What happens to the dog object?

Lunny
  • 852
  • 1
  • 10
  • 23
  • In this case, the first `person` instance will be flagged on the first GC cycle, and removed on the second. Unreachable values are removed automatically, there's nothing you need to do – Elias Van Ootegem Mar 17 '16 at 15:16

1 Answers1

2

JavaScript is a garbage-collected language. You don't have to manage memory yourself (and in fact, there are not even any operators that would let you do it).
Objects that are unreachable (such as your first new person() after the only variable pointing to it was overwritten) will automatically be cleaned up.

For details, see also How does garbage collection work in JavaScript? and What is JavaScript garbage collection?.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Maybe this is a question for itself but can you manage memory with the `delete` keyword? – A1rPun Mar 17 '16 at 15:15
  • 1
    @A1rPun The delete keyword can be used, but it's not recommended. Using `new` and `delete` generally is a sign that the code was written by someone who doesn't quite understand JS, TBH – Elias Van Ootegem Mar 17 '16 at 15:18
  • 1
    @A1rPun: No. [The `delete` keyword is about object properties](http://perfectionkills.com/understanding-delete/), it has nothing to do with memory. – Bergi Mar 17 '16 at 15:20
  • @EliasVanOotegem: "Can be used" is ambiguous. No, it doesn't do what a C++ programmer would expect. Yes, it can be used to the same extent as `= null;` (but neither one forces garbage collection on the former value). – Bergi Mar 17 '16 at 15:21
  • @Bergi: Was writing an answer to explain that `delete` doesn't do what the OP thinks it does. I agree that _"can be used"_ is ambiguous – Elias Van Ootegem Mar 17 '16 at 15:32