Let’s say I start up a var for an Object in my code
var base = {x:Infinity, y:Infinity};
and later in the same scope I do
var base = {x:0, y:0}
I get that I can re-use the existing variable, but I’m trying to iterate on a point.
- Does this cause any problems for the current scope as far as memory is concerned?
- Would there be any problems if these are in different scopes?
- Is the general rule to never use var on an already-existing variable?
- If I did this several (thousands) of times, would I run into any “funky” issues?
It releases its hold on the old value, so it can be potentially garbage collected. I say potentially, because objects can be referenced by different variables.
If they’re in different scopes, the inner
basewill shadow the outer one (assuming you’re talking about nested scopes), so the old value will not be overwritten. Shadowing is usually best avoided.Generally, within the same scope, yes but that’s more of a coding style aspect. It won’t make an effective difference in the execution since there’s only one declaration no matter how many times you declare the same
varin the same scope.Depends. Are you talking about overwriting in a loop? If you no longer need the current value, it shouldn’t be an issue.
To be clear, when you do this:
What’s really happening is this:
Note that when I talk about scope and
var, I’m talking specifically about function scope. In standard JavaScript/ECMAScript implementations, there is no block scope, so there’s no special meaning when usingvarin aforstatement for example.As mentioned by @Charles Bailey, Mozilla has
let, which does allow scoping in blocks, but it would require that specific keyword. Thevarstatement doesn’t recognize the block with respect to variable scope.