David Panart David Panart - 2 months ago 10
Javascript Question

How to set a referenced variable to null?

here is my use case :

on Phaser.io, when a user hit a button, I set a Phaser.sprite to a local

let newSquare
variable, and I
.push()
it to the
Squares
array of Phaser.sprite.

Later, I call some
destroy
function on that
newSquare
variable, and then I set it to null. While the sprite is well removed from the screen after the
.destroy()
, I can still access it from my
Squares
array...

I thought that, being an object if I set the
newSquare
variable to null, it'd be set to null for all the other references too, shouldn't it ?

So why is my ref in the
Squares
array not set to null ?

Excerpt :

eventFunction ( e, i ) {
let newSquare = Game.add.sprite( Lines.attack.a, 0, 'square');

// Some other methods call here
Squares[ e.target.dataset.line ].push( newSquare );

setTimeout( () => {
if ( newSquare ) {
newSquare.destroy();
newSquare = null;
console.log(Squares); // will print an array with an iteration corresponding to newSquare object, when I want it to be set to null, in order to clean the array with a _.pull()
}
}, ( 2 * 1000 ) );

}


What am I missing here ? Thanks you.

Answer

You're only nullifying the reference to the object that was originally created. The object still exists in memory and has a reference to it through array access. This means that it won't get garbage collected. You will need to nullify it within the array...

I'd say keep the reference to the item in memory and use that reference to find the index of the object within the array that you pushed to. E.g.,

array.find(el => el === reference)

...where reference is the identifier that you were previously assigning to null.

A way to nullify the element and maintain its current position within the array is to map over your collection using the reference to locate your item. E.g.,

array.map(el => el === reference ? null : el)

If you're looking for a mutative way to modify the element in-place, use a forEach(..). E.g.,

array.forEach(el => {
  if (el === reference) {
    el = null;
  }
  return;
});