Hello.
Is it possible to destroy a JavaScript object and free up memory? If so, how?

    4 answers 4

    If this is really necessary and it does not damage the integrity of the code - the garbage collector will do everything for you.

    Otherwise - most likely it is a waste of time (believe javascript is now optimized enough to adequately cope with this task)


    And after that you even had such thoughts? If some code does not work fast enough or eats a lot of memory, the code is most likely to blame, not some object.


    For a variable to have a value of uncertainty, it is enough for it (oddly enough: D) to assign uncertainty, i.e. eg:

     var someObj = {someValue1: 0, someValue2: 1}; console.log(someObj); // -> { someValue1: 0, someValue2: 1 } someObj = undefined; console.log(someObj) // -> undefined, теперь (someObj === undefined) === true // но, надо знать и понимать, что undefined != false // -> true 

    To be able to use a condition like if(!someObj) , it’s enough

      someObj = false; // теперь - !someObj === true 
    • I need to make a variable like "undefined" - Anton Mukhin
    • Feel free to ask - why? - Zowie
    • Well, according to the logic of the application, it should be more beautiful to come out. Such a situation: There is some object. After using it, it is "deactivated". Then, when you need to use this object again, you need to recreate it. Than to create some flags denoting the need to create it anew you just want to do this: `if (! This.myObj) this.myObj = new ........` - Anton Mukhin

    Judging by your goal, you can just write myObject = null . This automatically reduces the number of references to the object (ie, if there are no more references, it will be released by the garbage collector in the near future).

    Accordingly, you can use an if (myObject == null) ... type to support your logic if (myObject == null) ...

      Directly - you can not ...

      You can manually remove all references to it, and after a while the garbage collector will remove it itself)

        delete obj; - you mean it?

        • This deletion of the link and the property, not the object - timka_s
        • Well, why? var o = {abc: 1}; console.log (o); delete o; console.log (o); - ling
        • one
          Deleting a variable is impossible ... - timka_s