What is the process for making a referenced variable null?

My scenario is as follows:

When a user clicks on a button in Phaser.io, I create a new Phaser.sprite and store it in a local variable called newSquare. This new sprite is then added to an array called Squares.

At a later point, I call a function to destroy the newSquare sprite and set the variable to null. Even though the sprite is successfully removed from the screen after calling destroy(), I am still able to access it from the Squares array...

I believed that setting the newSquare variable to null would also affect all other references to it since it is an object. Why is the reference in the Squares array not being set to null?

Here is an excerpt of the code:

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

      // Other methods are called here
      Squares[ e.target.dataset.line ].push( newSquare );

      setTimeout( () => {
        if ( newSquare ) {
          newSquare.destroy();
          newSquare = null;
          console.log(Squares); // The array iteration corresponding to newSquare object is still present when it should be set to null to clean the array with _.pull()
        }
      }, ( 2 * 1000 ) );
}

What am I overlooking here? Thank you.

Answer №1

When you nullify a reference to an object, the original object still exists in memory and is accessible through array access. This prevents it from being garbage collected. To effectively nullify the object within the array...

Let's simplify the issue with an example:

let x = {a: 1, b: 2, c: 3};
let y = x;

x = null;
console.log(y);
// => {a: 1, b: 2, c: 3}

To maintain the reference to the item in memory and locate the object within the array that was pushed, consider using:

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

In this case, reference is the identifier that was previously set to null.

If you need to nullify the element while keeping its position in the array intact, you can map over the collection using the reference. For example:

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

For a mutative approach to modifying the element directly in the array, use forEach(..). For instance:

array.forEach((x, i, arr) => {
  if (x === reference) {
    arr[i] = null;
  }
  return;
});

The forEach function will iterate over each element in the array. To optimize this process, you can consider using a loop with indexOf.

const i = array.indexOf(reference);
array[i] = null;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Clicking on a marker in Google Maps will display the address

I have a map that contains several markers, each designated by their latitude and longitude coordinates. I would like to be able to see the address associated with each marker when I click on it. However, I am currently experiencing an issue where nothing ...

Utilizing cheerio to set outerHTML in HTML

Could someone kindly assist me with setting the outerHTML of an element using cheerio? I seem to be encountering some issues with this process. For example, let's consider the following HTML structure: <div class="page-info"> <s ...

Guide to configuring Ionic Auto Height Sheet modal in Vue 3

Trying to implement an Ionic Auto Height Sheet modal in a Vue 3 project (https://ionicframework.com/docs/api/modal#auto-height-sheet). Below is the code I have written. In ion-tab-button #3, I included id="open-modal". Underneath the ion-tab-but ...

Tips for shrinking a sticky header when scrolling using Angular and JavaScript

Looking for a way to modify the header component in an Angular application so that it shrinks as the user scrolls down while maintaining its sticky functionality. How can I adjust the display of the lower half of the header to show no text when the user s ...

Begin with the constant element within the array initialization

What is the reason for the compiler (VC++) disallowing (error C2975) const int HASH[] = {24593, 49157}; bitset<HASH[0]> k; and how can I resolve this issue (initializing templates with constant values from an array)? ...

What is preventing me from loading Google Maps within my Angular 2 component?

Below is the TypeScript code for my component: import {Component, OnInit, Output, EventEmitter} from '@angular/core'; declare var google: any; @Component({ selector: 'app-root', templateUrl: './app.component.html', st ...

Ways to prevent onMouseDown from triggering when the element is exclusively clicked?

I'm currently working on developing a game where units (svg elements) are controlled using React. In this game, the units should be draggable, and clicking on a unit should open a form. However, when I click on the unit, only the mousedown event is t ...

What is the best way to display the time of a post update similar to the style of

I am currently working on creating a notification deck. Instead of displaying the time when a notification was received, I aim to show the time that has passed since its arrival similar to how Twitter and Facebook do it with formats like "32m" or "1 hour a ...

Decoding JSON Data in Angular 2

I am facing a challenge where I have an array of JSON objects that need to be parsed into my Tournament class. The Tournament class has the following structure: export class Tournament { constructor (public id: number, public name: string, ...

What is a sleek method for including a key and value pair to an object using an array?

In a project using angular2/typescript, I am working with an array of objects that contain key/value pairs from a database. These values are then displayed in a table on the UI using ag-grid-ng2. The table headers are dynamic and set in the database. One ...

What exactly is the function of the NextPage feature in Next.js?

Recently, I began incorporating TypeScript into my Next project. Could someone clarify the purpose of the following code snippets for me? import { NextPage } from 'next'; export const Page: NextPage = () => {} After reviewing the documentation ...

Attempting to update an AJAX field with the returned value, but it only updates after clicking away from it

Image of form utilizing AJAX & JS The current setup involves a maintainer that uses AJAX to update the "Calc" field in response to a number entered in the "Order No" field. The issue is that the "Calc" field does not update immediately after typing in the ...

Leveraging ng-hide in Angular to show or hide elements based on the state

Is there a way to utilize the ng-hide directive based on the value selected in a dropdown menu? Specifically, I am looking to display #additional-option if option C is chosen from the dropdown list. <div class="form-group"> <label class="co ...

Tips for retrieving the selected option from a dropdown menu

I have a dropdown menu with checkboxes that can be selected using SumoSelect. Here is the markup for the dropdown menu: <select multiple="multiple" name="somename" id="uq" class="select"> <option value="volvo">Volvo</option> <o ...

Steps to invoke a function in a PHP file from an external JavaScript file

Can anyone assist me with calling the function below in my PHP file? function update_hidden_input(saved_tokens, hidden_input) { var token_values = $.map(saved_tokens, function (el) { //alert(el[settings.tokenValue]); return el[ ...

Returning data to be displayed in Jade templates, leveraging Express and Node.js

Yesterday, I had a question. Instead of using next() and passing an Error object, I decided to figure out what it was doing and replicate it. So now, when someone logs in and it fails, I handle it like this: res.render("pages/home", { ...

Issue: Undefined onClick function for HTML when using Node.js, NPM, and Parcel

I am currently working on a weather application using Node.js, NPM, and Parcel for development. To ensure OpenLayers functions properly, I need to incorporate these technologies, even though I'm not very familiar with them. One key aspect of my proje ...

Issue with dynamic form JavaScript functionality after removing curly braces { } from a select tag in Rails

In my Rails form, there is a gender field defined as follows: <%= f.select :gender, ["Male","Female"],{class: "gender"} %> I also tried adding an onclick event like this: <%= f.select :gender, ["Male","Female"],{class: "gender"},onclick: "categ ...

Error message: AngularJS Jasmine spyOn: number has no functionality

I am encountering difficulties while attempting to execute a test that utilizes a mockup for a service call (retrieving location data from a web SQL database). Below is the controller code: .controller('LocationDetailCtrl', function ($scope, $s ...

Using JavaScript to send formatted text through POST requests in a Rails application

Within APP A, I have the following formatted text: A beautiful painting because I created it because an artist endorsed it because my cat loves it I can access this formatted text in index.html.erb through product.body_html, which I then load into a Ja ...