so, in this post here people are discussing the fact that
A = [1,2,3];
and then doing
A = [];
will not reset the array but create a new one.
My question is, if I use a global object variable
myglobals = { A : [] }
Can I safely reset the array with
myglobals.A = [];
Right? Since that's referencing the same object property and thus I'm not actually creating a new array, am I?
Update to question due to remarks below
Since there is a general consensus that splice(0) is the way to go, and since a very similar question has an answer that explains the impact to browser freeing up memory, I'm wondering if it's generally safe and proper to set any defined object (whether array or function or string, etc...) to null in order to reset it's value while retaining it's reference?
You are creating a new array. If you want to truncate the array, just set its length to zero:
var a = [1,2,3];
a.length = 0;
// a is now []
In your example with object properties, it's just the same. There are no pointers in JavaScript, just reference values. So the value of myglobals.A is a reference to an array. When you assign a new array to it, that value becomes a new reference, to a different array.
Nope, this still creates a new array. The important factor is the assignment, not the scope to which the "A" variable is attached. As long as you do something that looks like something = [], the JavaScript engine is going to manufacture a new Array object (the [] part) then assign a reference to it to something.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With