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?

1
  • 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 Commented Mar 17, 2016 at 15:16

1 Answer 1

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?.

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

5 Comments

Maybe this is a question for itself but can you manage memory with the delete keyword?
@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
@A1rPun: No. The delete keyword is about object properties, it has nothing to do with memory.
@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: 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

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.