简体   繁体   中英

Using let and const in short lived variables

Let's say I have a short lived variable that the GC will clean up pretty quickly, something like:

function doSomeThing() {
  var someValue = someCalculation();
  return someValue;
}

Now assume that someCalculation() is actually a placeholder for something that requires its return value to be set to a variable, or maybe something in react like:

render() {
  var someComponent = someValues.map(someComponentFactory());
  return (
    <div>    
      <someComponent />
    </div>
  )
}

In both cases someComponent and someValue are short lived variables that will be cleaned up once the function returns.

What's the right approach when using let and const ?

const makes sense because the value won't change, but let makes sense because you're not really setting a 'constant' value, it gets thrown away immediately.

I've tried to find something in the way the javascript engine works or some performance reason you'd use one or the other but I can't find anything.

So the question is, when declaring a immediately thrown away variable should you use let or const ?

Using const will not allow you to "help" garbage collection. Sometimes a pattern developers follow is to unset a variable to signal that the variable is ready to be garbage collected.

For example:

function doSomeThing() {
    let someValue = someCalculation();
    // pass off to another function
    anotherFunction(someValue);
    someValue = null;
}

If you were using const , you could not reassign someValue to null . However, when no more active code has reference to this, it will be garbage collected anyways which falls back to what you wrote originally. So the unsetting is really the only difference.

Here's a little snippet on the subject from You Don't Know JS :

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!

I would use const . For me, let is used to signal that you are creating a variable that is going to be changed. I never use it unless I have a good reason for creating such a variable.

For everything else, use const .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM