Reputation: 7490
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
?
Upvotes: 2
Views: 1108
Reputation: 18898
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!
Upvotes: 5
Reputation: 953
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
.
Upvotes: 1