What is the method of assigning values to objects using a variable that acts as a reference to them?

I apologize for the vague wording of this question, but hopefully you can follow along...

In my current project, I am creating a game engine using Javascript. Within this engine, there is a Scene object that contains various elements, including an array that holds all the items to be drawn.

To access this array, I use:

scene.internals.draw

The issue arises when this array needs to be manipulated within a specific method. Since the name/path of the array may change in the future, I wanted a solution that would allow me to update it easily without modifying multiple references throughout the code. To achieve this, I implemented the following approach:

var location = scene.internals.draw;

By storing the array path in a variable, I can make changes without impacting the overall functionality of the method. This method works well in most cases, such as adding objects to the array using .push(obj). However, there is a scenario where I need to divide the array, insert new elements, and then merge it back together, like so:

buff1 = location.slice(0, i); //First section of the array.
buff2 = location.slice(i, location.length); //Second section of the array.

//Inserting something between these sections.
buff1.push(ob);
location = buff1.concat(buff2); //Encountering issues here!

Initially, this logic functioned correctly when directly manipulating scene.internals.draw as the array path. However, after assigning a new value to the local location variable, the desired array was not being updated.

Therefore, my question is: How can I assign values to the actual objects themselves rather than just referencing variables like location?

Although one workaround involves updating the original array path manually at the end of the method:

scene.internals.draw = location.slice();

This approach requires repeating the array path and editing it twice, which is manageable but not ideal. For future scenarios where similar functionality may be required, I am seeking a more efficient solution.

Answer №1

In JavaScript, there is no actual assignment by reference available, which means you cannot directly accomplish this task. It may appear as if you are assigning by reference, but in reality, it is a copy of the reference value with certain consequences.

If you find yourself attempting to do this, it could be an indication of a more profound issue within your codebase that needs addressing, although I won't delve into that here.

One possible solution would involve using the following approach:

collection.splice(0, collection.length); // Clear all elements from the array
collection.push.apply(collection, buffer1.concat(buffer2)); // Concatenate and push buffers into the array

Answer №2

In the world of Javascript, there aren't any truly tangible objects - rather, there are simply objects and variables that store references to them.

By assigning a value to location, you're essentially creating another pointer to an object. The system doesn't keep track of the original object or any other variables pointing to it.

Therefore, when you change what location points to, you're only updating that specific reference. All other references to the same object remain unaffected and continue pointing to their initial location.

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

The 'formGroup' property cannot be bound in the LoginComponent because it is not recognized as a valid property of the 'form'

When working on my Angular project and using ReactiveFormsModule to create a form, I encountered an error message during the build process. The specific error was: src/app/security/login/login.component.html:11:13 - error NG8002: Can't bind to ' ...

Loading JavaScript asynchronously using ExtJS

I have created a custom widget using the ExtJS framework. In order to load the necessary ext-all.js script asynchronously, I wrote an embedd.js script that also combines other JavaScript files. I've attached a function to be called when Ext.onReady is ...

The functions Show() and Hide() may not work in all scenarios within jQuery

I'm currently developing a website that allows users to participate in quizzes. Each quiz consists of 20 questions divided into three sections: 1 mark for 10 questions, 2 marks for 5 questions, and 4 marks for 5 questions. For each question, there are ...

Error: The JavaScript engine Hermes is throwing a TypeError because it is unable to access the property 'navigate' which is undefined

Trying to set up react navigation has been a challenge, especially when attempting to move navigation items into their individual components. Below is a Stack Navigator within APP.js: import React from 'react'; import { StyleSheet, Text, View } ...

Nuxt router directing to incorrect URL upon refreshing the page

Let me show you exactly what I mean by setting up a demo Nuxt blog at https://example.com/nuxtblog/. This demonstration includes articles populated by the @nuxt/content package. The website has been generated statically using the nuxt generate command. Fol ...

JavaScript's prototypical inheritance model allows objects to inherit properties and

Exploring javascript's prototypical inheritance and object-oriented programming is new to me. I attempted to create a base object called Account and then inherit the CheckingAccount from it. Below is my code snippet. function Account(fName, lName) { ...

Highlight the title with a stylish CSS animation effect

I have a challenge with animating div tags once they come into view on the page. Thanks to waypoint.js, I have successfully achieved the 'in viewport' trigger, but now I need help with the animation part. Specifically, I am looking to add a grey ...

Refresh the content of an iframe (local HTML) by clicking on buttons

When a user clicks on a button, I am loading an HTML file into a DIV (iframe). The issue arises when the user clicks another button and wants to reload the iframe with a different HTML file. This is the current code snippet: <script type="text/javasc ...

Modifying an image with jQuery

Why won't this image change? Below is the relevant HTML, CSS, and jQuery code. HTML <nav id="desktop-nav"> <div class="logo"> <a href="#"></a> </div> <div> ... </div> ... CSS nav#desktop-nav . ...

Unusual Behavior of JavaScript for..in and enum

I'm facing an issue with the peculiar behavior of the for..in loop in JavaScript. Here's the structure of my HTML: <div id="quarter_circle_top_left">...</div> <div id="quarter_circle_top_right">...</div> <div id="quart ...

Gathering all posts related to jagi astronomy

Within my MongoDB database, I have a collection called "post." My goal is to extract all post IDs that are not disabled from this collection. To achieve this, I utilized Jagi Astronomy, a Meteor JS package, to create the schema. However, when I implemented ...

During initialization, React/Redux reducer produced an undefined value

Recently, I started working on my debut React/Redux project. Initially, everything was smooth sailing until I decided to implement a new reducer. The process seemed straightforward, but upon loading the page, an error popped up stating "Reducer X returned ...

Guide to defining API elements in Bootstrap 5 modal

I have been struggling with this issue for quite some time. I am working on a movie app and trying to implement a modal feature. Currently, I am able to display each movie individually along with their poster, title, and score. The goal is to have the mod ...

Module TypeScript could not be located

Currently, I am in the process of converting my nodejs project from JavaScript to TypeScript. I have updated the file extensions from .js to .ts, but now I am encountering errors with require(). In an attempt to fix this issue, I have added the following c ...

Send a JavaScript object to an MVC controller using an HTTP POST request

I'm encountering an issue while attempting to send a JavaScript object containing a string and a jstring to an MVC controller. Despite my code looking correct, I am receiving a null value in the controller. Any assistance would be greatly appreciated. ...

Using React refs to target multiple elements dynamically with the help of the map

My code effectively catches when the dropdown is clicked outside, and it's working well: displayOptions() { return _.map(this.props.selections, (option, index) => { return ( <div className="ui icon top dropdown" ...

When attempting to post a JSON array, Tomcat returns a 400 error code

My attempt to send the following JSON to Tomcat server resulted in a 400 error without even triggering the servlet - [ { "q": { "field": "uri", "value": "c:Data#part3" }, "uri_pre_select": true } ] ...

Tips for integrating html2canvas with Vue JS?

One hurdle I encountered was the absence of a shorthand for document.getElementById in Vue. To address this, I created a custom function similar to this one. Another challenge I am currently grappling with is the perceived limitations of the html2canvas do ...

When the Promise object is assigned to the img [src], the image may occasionally be set to null

I incorporate Angular into my Electron application. One of the components in my app contains an array called files, where each element is an object with a member named preview. This preview member is a Promise object that returns a file:// object. <mat- ...

What's the reason for seeing "1:powershell" in the terminal when using react.js?

Can anyone explain why the terminal shows "1:powershell" in react.js? https://i.sstatic.net/1LyHe.png https://i.sstatic.net/5K95B.png ...