27

In Kyle Simpson's new title, You don't know JS: ES6 and beyond, I find the following snippet:

WARNING Assigning an object or array as a constant means that value will not be able to be garbage collected until that constant’s lexical scope goes away, as the reference to the value can never be unset. That may be desirable, but be careful if it’s not your intent!

(Excerpt From: Simpson, Kyle. “You Don’t Know JS: ES6 & Beyond.” O'Reilly Media, Inc., 2015-06-02. iBooks. This material may be protected by copyright.)

As far as I can see, he doesn't expand on this, and 10 minutes on Google turns up nothing. Is this true, and if so, what does "the reference to the value can never be unset" mean exactly? I have got into the habit of declaring variables that won't be changed as const, is this a bad habit in real concrete performance/memory terms?

4 Answers 4

27

WARNING Assigning an object or array as a constant means that value will not be able to be garbage collected until that constant’s lexical scope goes away, as the reference to the value can never be unset. That may be desirable, but be careful if it’s not your intent!

That note sounds a bit more of a warning than is necessary (perhaps even a bit silly) and tries to make some sort of special case out of this situation.

With a const variable declaration, you can't assign to the variable something little like "" or null to clear its contents. That's really the only difference in regard to memory management. Automatic garbage collection is not affected at all by whether it is declared const or not.

So, if you would like to be able to change the contents of the variable in the future for any reason (including to manually remove a reference to something to allow something to be garbage collected sooner), then don't use const. This is the same as any other reason for using or not using const. If you want to be able to change what the variable contains at any time in the future (for any reason), then don't use const. This should be completely obvious to anyone who understand what const is for.

Calling out garbage collection as a special case for when not to use const just seems silly to me. If you want to be able to clear the contents of a variable, then that means you want to modify the variable so duh, don't use const. Yes, manually enabling garbage collection on a large data structure that might be caught in a lasting scope/closure is one reason that you might want to change the variable in the future. But, it's just one of millions of reasons. So, I repeat one more time. If you ever want to change the contents of the variable for any reason in the future, then don't declare it as const.

The garbage collector itself doesn't treat a const variable or the contents it points to any different than a var or let variable. When it goes out of scope and is no longer reachable, its contents will be eligible for garbage collection.

const has a number of advantages. It allows the developer to state some intent that the contents this variable points to are not to be changed by code and may allow the runtime to make some optimizations because it knows the contents of the variable cannot be changed. And, it prevents rogue or accidental code from ever changing the contents of that variable. These are all good things when used in an appropriate case. In general, you SHOULD use const as much as practical.


I should add the even some const data can still be reduced in size and make the majority of its contents available for garbage collection. For example, if you had a really large 100,000 element array of objects (that you perhaps received from some external http call) in a const array:

const bigData = [really large number of objects from some API call];

You can still massively reduce the size of that data by simply clearing the array which potentially makes the large number of objects that was in the array eligible for garbage collection if nothing else had a reference to them:

bigData.length = 0;

Remember, that const prevents assignment to that variable name, but does not prevent mutating the contents that the variable points to.

You could do the same thing with other built-in collection types such as map.clear() or set.clear() or even any custom object/class that has methods for reducing its memory usage.

14
  • 2
    +1 for "silly" :-)
    – Bergi
    Jul 28, 2015 at 20:49
  • 2
    This answer is inaccurate. See this answer: stackoverflow.com/questions/31686412/… Jul 12, 2016 at 1:23
  • 3
    @KyleSimpson - What is inaccurate about this answer? The question here is about const variables. The answer you link discusses closures. This question anticipates GC with closures in several ways, including the last two sentences. But, bottom line - if you want to assign to the variable, don't make it const. If you don't need to assign to it and want it protected, make it const. Not any more complicated than that.
    – jfriend00
    Jul 12, 2016 at 1:28
  • 3
    @KyleSimpson - const by itself does not change garbage collection at all. If you wanted to manually remove a reference that a variable points to, then don't make that variable const.
    – jfriend00
    Jul 12, 2016 at 1:44
  • 3
    @KyleSimpson - Do you think the GC treats a variable any different if it's const or var? Yes, you the programmer must do things differently with const or var, but not the GC. And, yes if you would like to set a variable to null sometime in the future to make something eligible for GC, then don't use const. Duh. My 2nd paragraph of my answer states that already. Any, what part of my previous comment do you think is wrong? FYI, I disagree with you, but I did not downvote your answer.
    – jfriend00
    Jul 12, 2016 at 3:57
13

That note in my book was referring to cases like this, where you'd like to be able to manually make a value GC'able earlier than the end of life of its parent scope:

var cool = (function(){
   var someCoolNumbers = [2,4,6,8,....1E7]; // a big array

   function printCoolNumber(idx) {
      console.log( someCoolNumbers[idx] );
   }

   function allDone() {
      someCoolNumbers = null;
   }

   return {
      printCoolNumber: printCoolNumber,
      allDone: allDone
   };
})();

cool.printCoolNumber( 10 ); // 22
cool.allDone();

The purpose of the allDone() function in this silly example is to point out that there are times when you can decide you are done with a large data structure (array, object), even though the surrounding scope/behavior may live on (via closure) indefinitely in the app. To allow the GC to pick up that array and reclaim its memory, you unset the reference with someCoolNumbers = null.

If you had declared const someCoolNumbers = [...]; then you would be unable to do so, so that memory would remain used until the parent scope (via the closure that the methods on cool have) goes away when cool is unset or itself GCd.

Update

To make absolutely clear, because there's a lot of confusion/argument in some comment threads here, this is my point:

const absolutely, positively, undeniably has an effect on GC -- specifically, the ability of a value to be GCd manually at an earlier time. If the value is referenced via a const declaration, you cannot unset that reference, which means you cannot get the value GCd earlier. The value will only be able to be GCd when the scope is torn down.

If you'd like to be able to manually make a value eligible for GC earlier, while the parent scope is still surviving, you'll have to be able to unset your reference to that value, and you cannot do that if you used a const.

Some seem to have believed that my claim was const prevents any GC ever. That was never my claim. Only that it prevented earlier manual GC.

9
  • 6
    Bottom line - if you want to assign to the variable, don't make it const. If you don't need to assign to it and want it protected, make it const. Not any more complicated than that. You're just defining one case where you might actually want to assign to it so don't make it const in that case. I stand by my statement that making something const does not change its garbage collection in any way. It does affect whether you can assign to it so if you wanted to assign something to it in order to get rid of what you had assigned to it previously, then don't make it const.
    – jfriend00
    Jul 12, 2016 at 1:32
  • 2
    It affects your ability to manually release a reference to it - yes - duh you can't modify a const variable. As I've said about 5 times. If you intend to change the value of the variable in the future for ANY reason, then don't use const. Otherwise, it is a great feature. Left by themselves, a const variable and var variable at the top of a function will be garbage collected at exactly the same time.
    – jfriend00
    Jul 12, 2016 at 4:03
  • 3
    @jfriend00 good grief, you still keep asserting that a variable gets GCd. It doesn't. Values get GCd. Variables that hold references to those values will prevent the GC. If those references can't be changed, the GC is prevented from happening earlier if you want it to. What I keep saying over and over is, "const affects GC because it prevents you from getting earlier GC, if you want it, for that value than scope teardown" Jul 12, 2016 at 4:07
  • 2
    @KyleSimpson: If you want to nitpick, variables are garbage collected with their scopes (or earlier depending on engine optimisations). So you'd have to say "const affects GC of the value because it prevents you from removing the reference, but it does not affect the GC of the variable". Both you and jfriend are right here, just stop arguing now :-)
    – Bergi
    Jul 12, 2016 at 4:43
  • 3
    @KyleSimpson Thanks for replying to this, Kyle. I understand the issue fully now, but when I read the book I really didn't. I don’t usually have a hard time understanding your writing – quite the opposite in fact – so maybe it would be worth expanding on this in the next edition/update to the book? Jul 12, 2016 at 7:08
11

No, there are no performance implications. This note refers to the practise of helping the garbage collector (which is rarely enough needed) by "unsetting" the variable:

{
    let x = makeHeavyObject();
    window.onclick = function() {
        // this *might* close over `x` even when it doesn't need it
    };
    x = null; // so we better clear it
}

This is obviously not possibly to do if you had declared x as a const.

The lifetime of the variable (when it goes out of scope) is not affected by this. But if the garbage collector screws up, a constant will always hold the value it was initialised with, and prevent that from being garbage-collected as well, while a normal variable might no more hold it.

10
  • 1
    Can you elaborate perhaps on "if the garbage collector screws up"? Does that happen? Is it only in rare, complex situations? Jul 28, 2015 at 21:00
  • 2
    @KyleSimpson: Where's the difference between someCoolNumbers in your answer and x in mine? The point that you (obviously) cannot explicitly nullify a const is the same.
    – Bergi
    Jul 12, 2016 at 1:28
  • 2
    @KyleSimpson: Sure, if the function closes over x (and there exists some point from which on calls to the function don't need x any more) helping the garbage collector is advisable even when the GC is not naive. But I still consider such situations to occur only rarely, most of the time the closure itself is collected anyway or the value is not large so that there is no memory leak that actually required the nullification.
    – Bergi
    Jul 12, 2016 at 4:34
  • 3
    @KyleSimpson: In such cases I'd say the performance implication is because the null assignment is missing, not because the variable was declared const :-) No, I didn't downvote your answer.
    – Bergi
    Jul 12, 2016 at 4:46
  • 2
    @KyleSimpson: The more likely reason it was missing is that the author forgot it… and had he not forgotten it, he'd have made the const a let. Or it might not be missing, throw an exception on const assignment, blow up the application - and there's no more memory that could leak :-P
    – Bergi
    Jul 12, 2016 at 5:00
8

The way garbage collectors (GC) work is when something is referenced by nothing ("cannot be reached"), the GC can safely say that something isn't used anymore and reclaim the memory used by that something.

Being able to replace the value of a variable allows one to remove a reference to the value. However, unlike var, const cannot be reassigned a value. Thus, one can't remove that constant from referencing the value.

A constant, like a variable, can be reclaimed when the constant goes "out of scope", like when a function exits, and nothing inside it forms a closure.

2
  • Thanks. Are you saying that Mr Simpson was only referring to a manual unsetting of a variable no longer being possible? As @Bergi says in his answer? Jul 28, 2015 at 20:58
  • 1
    Thanks for your answer, I had to accept the other really as it more directly answered my question but all the answers including yours were great! Jul 28, 2015 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.