In JavaScript, when assigning a value to an array element, does it create a copy of the element or

I'm uncertain about the wording to use in searching for a solution to this query. Here is the code snippet:

this.snake = [{x: 0, y: 0}];
var curhead = this.snake[0];

Is curhead holding a duplicate of the object at snake[0] or is it directly referencing it?

Answer №1

When it comes to JavaScript, the concept of copying by value is always implemented.

However, in JavaScript, objects such as Arrays are handled differently as they are accessed by reference. For example, if you create an array using foo = [], you are essentially generating an array and then assigning a reference to it to the variable foo.

Essentially, what you end up with is a copy of the first value within the array, which is essentially a reference to the object.


It's important to note that this is not the same as having a reference to the first value in the array.

For example:

var array = [ { value: 1 } ];
var reference = array[0];
array.unshift( { value: 2 } );

If reference was a reference to the first value in the array, any changes made to that value would reflect the object with value : 2.

However, since it is a copy of the value, it will still point to the object with value : 1 (which has now become the second value in the array).

Answer №2

When looking at the provided scenario, the variable curhead is assigned a pointer to the initial element within the array snake

Answer №3

This particular data structure consists of a single object within an array. Thus,

this.snake[0]

Will point to the object {x: 0, y: 0}.

Paragraphs

Answer №4

At this moment, both curHead and snake[0] are pointing to the same spot in memory. If you modify a value in curHead, it will also change snake[0].

curhead.x = 1
console.log(curhead)
//Object {x: 1, y: 0}
console.log(this.snake)
//[{x: 1, y: 0}]

When you try to assign a completely new object to curhead, like curhead = 'hi', JavaScript will allocate a new memory space for curhead, leaving this.snake unchanged with its value of {x: 1, y: 0}.

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

Tips for converting a select option into a button

Currently, I am working with Laravel to develop my shopping cart. My goal is to implement a feature that allows customers to select the quantity of a product and have the price update accordingly when they click on a specific number. However, I am facing a ...

Arranging an np.array of date values

I have a matrix containing dates that I want to sort by date and then return to its original format. data = np.array( [[2015, 1, 1, 23, 4, 59], [2015, 4, 30, 23, 5, 1], [2015, 1, 1, 23, 5, 25], [2015, 2, 15, 58,5, 0], [2015, 5, 20, ...

Transform JSON data into a Google Sheet using Google Apps Script

Having trouble inserting the JSON response into Google Sheet using Google Apps Script with the code below. Running into errors, even though I can't seem to pinpoint the issue. Take a look at the screenshot and code snippet provided: function myF ...

Unlocking the data within an object across all Components in Vue

Recently, I've started using Vue and encountered a problem. I'm trying to access data stored inside an Object within one of my components. To practice, I decided to create a cart system with hardcoded data for a few games in the app. Below is the ...

What is the best way to manage photos from your phone without having to upload them online?

I'm currently developing an application using AngularJS/Javascript, HTML, and CSS within a cloud-based environment on c9.io. My next task is to create and test an app that can access the phone's photo album, apply filters to images, and I'm ...

Scroll a div using JavaScript/jQuery

I'm currently facing some challenges in resolving this issue. My goal is to pan a DIV using jQuery. The process is quite straightforward - on mouseDown, I capture X & Y coordinates and then subtract them from the newly obtained X & Y values during mou ...

Tips on sending arguments to functions associated with ...mapActions...()?

After analyzing the passage below export default { methods: { ...mapActions(["updateData", "resetData"]); } } I wanted to include a parameter in the called functions. Unsure of the proper way to do this while still using the ...mapAction() call, ...

Populating the array by calculating the average values

I'm encountering an issue in my JavaScript code. I have a situation where I must fill gaps in an array with the averages of the surrounding values. Let me provide an example: Array: 1, 2, 3, ,4, 5 In this case, I would need to fill the gap with the ...

Unable to generate package.json

After attempting to set the execution policies to unrestricted, I was able to resolve my dummy server error, but I encountered an issue creating package.json. The output is displayed below. Please note that I tried both npm init and npm init -y PS C:&bso ...

Is it possible to display a pdf.js page as actual HTML elements rather than as canvas or SVG?

I am in the process of creating a user-friendly mobile interface for pdf reading. However, I want to incorporate more advanced features by developing my own pdf reader instead of relying on the pdf.js team's viewer. Is there a method available to rend ...

A guide on implementing a jQuery click function on ng-click in an AngularJS application

Currently, I am developing a mobile app and utilizing MDL for the app's UI along with Angular JS. The theme I purchased from ThemeForest is called "FAB." My goal is to display data from the server using API's and showcase all the products that ar ...

I am looking to build an array that can store five numbers inputted by the user. Following that, I want to utilize a for loop to display the contents of the array. How can I accomplish this task?

Looking for help to store 5 unknown numbers in an array and then display them after the user has entered all 5 numbers. Can anyone assist me in creating an array of size 5 and using a for loop to show the numbers? Here is the code I currently have: ...

Error: The function expressJwt is not recognized as a valid middleware

As I delve into learning about middlewares, I encountered an issue when trying to import express-jwt. The syntax I used was: const expressJwt = require('express-jwt') To address the problem, I uninstalled the current version of express-jwt and i ...

Tips for managing, showcasing, and modifying checkbox controls within an AngularJS environment

I have successfully completed the saving part of the code. Below, I am demonstrating how I displayed the saved data and my attempts to edit the form upon clicking the edit button. Here is my AngularJS code: var module = angular.module('myApp&apos ...

Dynamic content modal

Recently, I started exploring react native. In my application, there are 5 buttons on the screen. Each of them triggers the same <Modal>, but the content inside it changes based on the button clicked. For example, if I click the first button, a tex ...

Tips for displaying a page within a parent div upon clicking a button in a child div

Hey there, I'm new to scripting and I've run into a problem. I'm trying to figure out how to load a page in a parent div when clicking buttons in a child div. Specifically, I want to load a specific page in the parent div. Just to clarify, t ...

Problem with the content-editable attribute

My goal is to make each div with the class .edit editable by adding the contenteditable property: $(document).ready(function() { $(".edit").attr("contenteditable", "true"); }); However, after applying this, I found that clicking on a div with content ...

Enhance dynamically generated HTML using jQuery Mobile

Using jQuery Mobile version 1.2.0 I am dynamically generating HTML using JavaScript ($(selector).html(content)), adding it to the DOM, and then displaying it ($.mobile.changePage()). After that, I make an AJAX call, retrieve some data, and re-generate th ...

Leveraging JavaScript and Thymeleaf to manipulate a list

I am trying to access an object from a list in JavaScript, which is being passed from the controller. Currently, I am working with Thymeleaf and Spring Boot. The list is named ${collaborateurs}. The following code snippet is functional: <script th: ...

Ensure that clicking on an element closes any currently visible elements before opening a new element

Take a look at my code snippet below. I am working on creating multiple clickable divs that reveal different content when clicked. However, the issue I am facing is that currently, both content blocks can be displayed simultaneously. My goal is to have onl ...