When I provide an array as an argument to a JavaScript function, it appears that the array remains unaltered. Isn't it supposed to be passed by reference?

My class includes a JavaScript function that should manipulate the array it receives by reference, but it doesn't seem to be working as expected:

this.filterEqualCities(this.birthCitiesNames, this.birthCitiesPositions);

  filterEqualCities: function(citiesNames, citiesPos) {
    var tempNamesArray = [];
    var tempPosArray = [];
    for(var i=0; i<citiesNames.length; i++) {
      var name = citiesNames[i];
      name = name.split(',')[0];
      if(tempNamesArray.indexOf(name) == -1) {
        tempNamesArray.push(name);
        tempPosArray.push(citiesPos[i]);
      }
    }
    citiesNames = [];
    citiesPos = [];
    for(var i=0; i<tempNamesArray.length; i++) {
      citiesNames.push(tempNamesArray[i]);
      citiesPos.push(tempPosArray[i]);
    }
  }

Answer №1

When you execute the following code:

citiesNames = [];
citiesPos = [];

The variables no longer point to the original arrays that were provided, instead they now reference these two empty arrays.

If you wish to clear the original arrays, you can achieve this by simply setting their lengths to 0:

citiesNames.length = 0;
citiesPos.length = 0;

Answer №2

Building on what @Barmar mentioned in their insightful response - the crux of the issue lies in the fact that arrays and other objects in Javascript are not actually "passed by reference" despite appearances suggesting otherwise. While commonly stated as such, they are passed by value just like any other variable. However, this "value" itself serves as a "reference" to a specific value stored in memory, rather than to the variable itself.

For instance, if you were to make changes to the citiesNames array, such as adding a new element using push, this modification would be reflected externally because you are altering the shared value that both the local and global citiesNames variables point to.

On the other hand, when you execute citiesNames=[], you are essentially assigning a completely new value to the local citiesNames variable. As a result, the other citiesNames variable remains unaware of this change.

This behavior is not exclusive to Javascript. In fact, Python exhibits similar characteristics (and potentially other programming languages as well, although my familiarity with them is limited).

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

Converting a nested JSON array into a flat structure with Elastic Search and JavaScript

I am struggling to flatten my elastic query response and extract only the _source details into a single-level array. Below is an example of the elastic response: Although I can access an array of data using (response.hits.hits), I am having trouble flatt ...

A guide on accessing a particular element within an array using MikroC

I'm having trouble working with an array in MikroC. The array I'm trying to work with is defined as follows: char array[4] = {'1','1','0','\0'}; My goal is to extract a specific element from ...

Implementing jQuery getScript in a Ruby on Rails 3 application

After watching a railscast tutorial on loading records through ajax when a link is clicked, I implemented the following javascript: $(function() { $("#dash_container th a").live("click", function() { $.getScript(this.href); return false; }); } ...

Confidently set up a proxy that is recursively nested and strongly typed

I have a collection of objects where I store various content for a user interface. Here is an example: const copy = { header: { content: 'Page Header' }, main: { header: { content: 'Content Subheader' }, body ...

Setting up paths to bypass authentication on an Express website

Currently, I am in the process of developing an application using node and express. I have implemented a passport authorization middleware for all routes as part of my highly modular approach to building the app. One challenge I have encountered is when tr ...

Getting rid of background color in a tooltip using Material UI

I'm currently tackling an issue with Material UI's tooltip. I can't seem to find a way to make the background of the tooltip completely transparent. By default, it displays with a grey background and white text. Changing the background color ...

Every time I try to call the event in jQuery for the second time, it fails to work

I am currently working on a website that features an image gallery powered by the jquery wookmark plugin with filtering capabilities. Recently, I integrated the colorbox plugin (which was provided as an example by wookmark) to enhance the user experience. ...

Removing an object from an array if it does not exist in another array: A step-by-step

Looking to remove an object from an array if it's not present in another array. After doing some research, I came across a similar question on this link, but with a different array source. Below is the example from the link: var check = [1, 2, 3]; ...

Display and conceal individual divs using jQuery

Despite my lack of experience with jQuery, I am struggling with even the simplest tasks. The goal is to display/hide specific messages when certain icons are clicked. Here is the HTML code: <div class="container"> <div class="r ...

The program encountered an issue trying to change a string into a float value

In my Python script, I created 2 columns and converted them into an np array. Then, I successfully saved them in a new file. fi = np.array([co,pred[40]]) fi=fi.T np.savetxt("Pred_40.dat", fi, delimiter=" ") Now, my goal is to develop a ...

To give an element a class in Javascript (without using jQuery) if it is currently hidden

Apologies if this question is not perfect, as I am still learning. I have been struggling to figure out how to add a class to an ID when the class is hidden using pure JavaScript (without jQuery). Below are my attempts so far: function hidekeep() { ...

Tips for passing parameters in an AJAX request

I have a single AJAX call that requires passing parameters to my function. Below is the AJAX call implementation: $.ajax({ url: 'lib/function.php', data: { action: 'getStoreSupplyItems', id: store_id, ...

Incorporating TWEEN for camera position animations: A complete guide

function adjustCameraPosition(newPosition, animationDuration) { var tween = new TWEEN.Tween( camera.position ) .to( newPosition, animationDuration ) .easing(TWEEN.Easing.Linear.None) .onUpdate(fun ...

Employing the Map function in React leads to an error that is undefined

Upon simplifying my code, it seems that I am encountering an unresolved issue with the map function being used in different locations. I have noticed that code from examples running on platforms like Codepen does not work in my locally created react app p ...

The value stored in $_POST['valuename'] is not being retrieved

Having recently delved into ajax, I am encountering some difficulties in making it function properly. The objective of the code is to send two variables from JavaScript to PHP and then simply echo them back as a string. However, instead of receiving the e ...

Searching Text Boxes with Javascript: A Better Way to Handle Arrays

I'm struggling to implement a feature where users can search for authors in a database and be redirected to the corresponding HTML if found. Otherwise, it should display a message saying "No Author Found"... I need some assistance in getting this fun ...

Updating the textarea with Ajax without the need for a button click or refreshing the

I need to implement a feature where a textarea will automatically update the database without requiring the user to click on any buttons or refresh the page. The idea is that after a keyup event, there should be a 2-second countdown timer. If no additional ...

What is the best approach to comprehensively organize a multidimensional list in Python while maintaining efficiency and cleanliness?

For instance: Given the following array elements: array = [[10, 9, 1], [2, 1, 1,], [4, 11, 16]] I want to transform it into: print array [[1, 1, 1], [2, 4, 9], [10, 11, 16]] Can I achieve this using the list.sort() function or would I need to c ...

Obtain the native element of a React child component passed through props, along with its dimensions including height and width

Is there a way in React to access the native HTML element or retrieve the boundaries of an element passed as a child in props? Consider the following component: class SomeComp extends Component { componentDidMount() { this.props.children.forEa ...

Tips for effectively passing "this" to direct the event initiator in react js?

I'm facing an issue where I am attempting to send a buttons object to a function and then access its properties within that function. Here's my button : <RaisedButton label="Primary" id = "1" onTouchTap={()=>this.buttonPress(this)} prima ...