Issue with clearing an array in JavaScript by reassigning it when accessed through a different reference variable

I discovered a workaround - by directly accessing the original array variable, I was able to achieve the desired result. Despite this, I am still intrigued by the reason behind this behavior.

var array = ["hello"];

var testObject = {arr: array};

testObject.arr = [];

console.log(array) still shows ["hello"] instead of [] as anticipated.

Nevertheless, this approach DOES successfully clear the array

while (testObject.arr.length > 0) {

   testObject.arr.splice(0, 1);

}

console.log(array) now displays [] as expected.

Could someone elucidate what is happening here? Thank you!

Additionally, when I run testObject.arr.push("testing"), it behaves as expected....

I am puzzled as to why trying to reassign the array does not work.

Answer №1

testObject.arr = [] assigns an empty array to the arr property of testObject, creating a new array and not affecting the previous value of the property. This action changes the state of testObject.

On the other hand, testObject.arr.splice modifies the array directly, affecting the array stored in that property.

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 data provided was deemed incorrect. Modifying the function to include file uploads in Laravel 8 and Vue 2

I've been attempting to create an update function that includes file upload capability. Here is what I have experimented with so far: <b-form @submit.prevent="update" enctype="multipart/form-data"> . . . . <b-form-f ...

Steps for submitting a form once all inputs have been verified

$('#f_name, #l_name').change(function(){ if($(this).val().length < 2) { $(this).css('border', '1px solid red'); alert('names must be at least 2 symbols'); check ...

what is the method to extract the value of a JSON object nested within another JSON object

Can someone please assist me? "_attachments": { "kiran.jpg": { "content_type": "image/jpeg", "revpos": 6, "digest": "md5-mEsoX4ljN1iJlF2bX1Lw2g==", "length": 4601, "stub": true } } I ...

The functionality of jQuery typeahead ceases to perform after I choose an option from the dropdown menu

Initially, my jQuery typeahead autocomplete function works perfectly. However, after selecting an option from the list, it fails to show results when I try to use it again by typing in the input field. It seems like the typeahead functionality gets destro ...

billboard.js: The 'axis.x.type' property is conflicting with different data types in this context

axis: { x: { type: "category" } }, An issue has arisen: The different types of 'axis.x.type' are not compatible with each other. The value of 'string' cannot be assigned to '"category" | &qu ...

Successfully Determining User Identity with Ajax Authentication

Currently, I am facing a security issue with my login page that uses an Ajax request for user authentication. The password entered by the user is sent as plain text in the form data of the Ajax request, making it vulnerable to interception by sniffing tool ...

How can you identify duplicate entries using Mongoose?

I am currently working on a create function and encountering some code that closely resembles this: if(req.body.test !== undefined) { if(--req.body.test EXISTS IN test (model)--) { DO STUFF } else { ...

Guide on removing an item from a list using a JavaScript button

I am in the process of creating a basic task list that allows users to input tasks. When the add button is clicked, the task will be added to an unordered list along with a delete button. As a beginner in JavaScript, I am struggling to figure out how to ma ...

Is it feasible to determine the specific memory address of an Object in a program?

Is it possible in JavaScript to determine the memory location and memory usage of an object? Any assistance on this matter would be greatly appreciated. ...

AJAX request function is only successful on the first attempt

Currently, I am implementing AJAX functionality to verify whether a user-input ID exists in the database. If the ID is found, a check mark is displayed; if not, a cross mark is displayed. The issue arises when I input an ID for the first time, which is pr ...

JQuery selecting and highlighting a row within a dynamically loaded table via ajax

On a webpage, there are two tables being displayed. The first table loads along with the entire page, while the second table is loaded later on using ajax. Each row in both tables contains links. Upon clicking a link, the corresponding row in the table ...

Having trouble with AJAX integration when adding two products to the cart? Looking for a solution to resolve this issue?

In the cart view page, I have noticed that when there is only one product in the cart, I am able to increase and decrease the quantity by clicking on the + and - buttons. However, if I add more than one product to the cart, these buttons do not work for an ...

Move a <div> using a handle (without using JQuery)

I devised a plan to create a moveable div with a handle and came up with this code snippet: var mydragg = function() { return { move: function(divid, xpos, ypos) { divid.style.left = xpos + 'px'; divid.style.top = ypos + &apo ...

Can Angular retrieve the inner HTML content of an element?

Check out this demo . In this demonstration, I have created a list of "names" and I'm trying to retrieve the text of the selected element. However, whenever I click on an item from the list, I consistently get the same "innerHTML" for all users. Is ...

Sending an email through Node.js with SendGrid is not a challenge

I've got this Mailer.js file const sendgrid = require('sendgrid'); const helper = sendgrid.mail; const keys = require('../config/keys'); class Mailer extends helper.Mail { constructor({ subject, recipients ...

Is it necessary to re-export a module after modifying an attribute in it in JS/ES6?

From my understanding of the module system, when I use import 'some_module' in a file, I will always receive the same instance of that module and not a new instance each time. However, I am a bit puzzled by a pattern I have observed in certain a ...

How can I access the object that created an interval from inside an interval callback function?

I am facing a challenge with JavaScript as a beginner. I am working on a React App and trying to add a timer feature to it. I have successfully created the timer functionality, but the issue lies in the timer callback (similar to this query: setInterval in ...

Steps to update the value of an object stored within an array

I have a collection of items stored in an array. Each item is represented by an object with properties. I want to update the value of a specific property within each object: var array=[{a:1, b:false}, {a:2, b:true}, {a:3, b:false}] My goal is to set the p ...

Array specifically designed for replacing strings, but it only works with the final element

Here is a snippet of code I am working with: $(document).on('click','.submitMessage,.submitStdMessage', function(e){ prevContent=$('textarea').val(); alert(prevContent); variables = { '{nom}' ...

What is the best way to create and implement custom declaration files that are not available on @types or DefinitelyTyped?

I have encountered a situation where I am using an npm package named foo that is not available on DefinitelyTyped or may be outdated. Despite this, I still want to consume it under stricter settings like noImplicitAny, so I need to create custom definition ...