Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

correctly resetting a global variable in javascript?

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?

like image 697
tim Avatar asked Jun 13 '26 01:06

tim


2 Answers

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.

like image 131
bfavaretto Avatar answered Jun 14 '26 15:06

bfavaretto


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.

like image 43
Jollymorphic Avatar answered Jun 14 '26 17:06

Jollymorphic