"Understanding Global Variables in Javascript and the Impact of Overwriting when Using Splice Method

Struggling with a baffling issue that has me stumped, so any assistance would be greatly appreciated.

  • At the beginning of my script, I establish a global variable called '_raw'
  • (Using jQuery) I execute an Ajax request which returns JSON array data (I have verified that the JSON data is accurate)
  • I take this JSON response and assign it to _raw
  • Upon clicking a link, _raw is passed to a function, for example, function myFunction(dataArray), invoked by myFunction(_raw)
  • Inside this function, based on specific criteria, dataArray gets spliced (such as dataArray.splice(2,1))
  • The modified dataArray is then returned.

For instance:

var _raw;

// AJAX call populates RAW with an array like Apple, Banana, Pear, Pineapple, Coconut, Raspberry

myFunction(dataArray){
  var data=dataArray;
  data.splice(2, 1);
  return data[0];
}


$('a').click(function(){

  result = myFunction(_raw);
  alert(result);
// First time running this, 'Pear' is returned; however, second time, 'Coconut' is returned - as if the splice operation affects both _raw and myArray/data...

});
  • I acknowledge that there are some shortcomings in the code above, but it serves to highlight the problem at hand.

The issue I am facing pertains to the fact that, to my understanding, the only instance where _raw is altered is during the AJAX call. Yet, when calling the myFunction function and passing _raw, the splice action also seems to impact _raw itself. Why is this occurring?

Answer №1

When handling arrays in JavaScript, it's important to remember that they are always passed by reference. This means that when you assign an array to a variable, you're essentially creating a pointer to the original array and any operations performed will directly affect the original array.

To avoid unintended side effects, it's crucial to create a copy of the array before making any modifications. Depending on the content and structure of the array, you may need to use a method like deep copying as discussed here.

Answer №2

In JavaScript, arrays are passed by reference, which means that when you assign one array to another variable using var data = dataArray, it does not create a new copy of the array.

This also means that when you use methods like data.splice(2,1), it directly modifies the original array instead of creating a separate copy.

If you do need to create a copy of an array in JavaScript, you can use the .slice() method.

If your goal is to access a specific element in an array, you can simply use numeric indices like this:

function myFunction(dataArray){
    return dataArray[2];
}

Answer №3

splice() alters the initial array: check out

Unlike slice(), the splice() function modifies the original array and gives back a new array.

On a side note, it's not necessary to pass _raw as an argument of myFunction() because it's a global variable that is visible throughout.

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 an associative array in JavaScript to a string map in C++ with Swig: A step-by-step guide

In a situation quite reminiscent of this query, I am aiming to wrap a function using SWIG that accepts a map of strings to strings: void foo(std::map<std::string, std::string> const& args); Creating an alias for the map suffices for Python: na ...

Retrieve default HTML from an AngularJS directive

Currently, I am in the process of creating an AngularJS directive and require the ability to extract the HTML content of an element before replacing it with a template. For instance: <edit>Default title</edit> The structure of my directive is ...

jquery malfunctioning with items loaded through jScroll (infinite scrolling)

In my application built on Laravel 5.1, I have implemented jScroll for infinite scrolling functionality from jscroll.com. Along with this, I have included some jQuery code that should execute when the user clicks the 'Like' button for each post. ...

"Running experiments with Google Ads and Google Analytics scripts results in a blank page being displayed

Currently, I am working on a plain HTML file and conducting tests to ensure that the Google Ads and Analytics scripts are functioning correctly before implementing them on other pages. A colleague who has an AdSense account provided me with the script code ...

Creating mathematical formulas in JavaScript

How can the equation be translated into JavaScript? This is the proposed programming solution, but there seems to be an issue. var MIR = parseFloat(($('#aprrate').val() / 100) / 12); var paymentAmount = (MIR * $('#amounttofinance').va ...

Transforming the value of a property in a JSON object using JavaScript

I have a JSON object that I am trying to manipulate by changing the value of its property "quantity" "[{"name":"Butter","image":"/static/images/items/dairy/butter.jpg", "price":" 30 uah","quantity":"1","alias":"butter"}, {"name":"Chesse","image":"/stat ...

Learn how to incorporate conditions into your mapping function in React to retrieve a single result

Hello everyone, I have a task where I need to compare two collections. If the comparison returns true, I want to display solved, otherwise I want to display Available. First collection : (5) [{…}, {…}, {…}, {…}, {…}] 0: creatorUserI ...

Error message received while converting webm video to images using Kagami/ffmpeg.js: Unable to locate an appropriate output format for '%04d.jpg'

These are the current versions: node v12.9.1, npm 6.10.2, [email protected] Repository: https://github.com/Kagami/ffmpeg.js The code in decode.js looks like this: const fs = require('fs'); const ffmpeg = require('ffmpeg.js'); c ...

Utilizing Angularfire OAuth for Facebook authentication in login strategy

After successfully implementing the code below in the loginCtrl controller and login.html, I encountered some issues with setting up the workflow correctly. My goal is to achieve something like this: //check if the current $scope has authData //if so red ...

NodeJS MySQL failing to retrieve the most updated data post-write

I'm struggling to solve an issue where after performing data operations (create, update, delete) and then querying for the data afterwards, I receive the previous version of the data rather than the updated version. For example: Let's say I hav ...

Angular: Enhancing View Attribute by Eliminating Extra Spaces

I'm using an ng repeat directive to dynamically set the height in my code. <ul> <li ng-repeat="val in values" height-dir >{{val.a}}</li> </ul> app.directive('heightDir',function(){ return { restrict: ' ...

Google Scripts: Generating a set of data to include in an email

As a newcomer to Google Script and JavaScript, I'm on a mission to email a list of file names extracted from a spreadsheet. The names reside in a column within my sheet, and after defining a variable called "newfiles" to cherry-pick only the necessary ...

Issue with nested loop and dynamic allocation of 2D array

My current challenge involves a problem with writing values to a dynamically allocated 2D array. Strangely, it appears that the values are being stored in incorrect positions within the array. Although I am confident in my memory allocation and iteration ...

In order for element.click() to be successful, alert() must be called beforehand

Recently, I created a tampermokey script that keeps track of the i intervals and automatically clicks on the next video. However, it's quite strange that the script only works properly when the alert line is uncommented: var i = 1; setInterval(functi ...

Error: Unable to submit data as the function this.submitData is not recognized

Having trouble calling an async function in the mounted() lifecycle hook of Vue.js? Keep getting the error message: Uncaught TypeError: this.submitData is not a function. Here's the code snippet in question: <template> <section class=&quo ...

Inject the JavaScript template into an HTML page within a <div> element

Looking for a solution to format JSON API data listing books with title, author, and other properties into HTML? Utilizing ES6 backticks and JavaScript templating, the challenge arises when needing to display two cards per row on the HTML page. The issue l ...

The message of error is undetermined

Can someone help me with using the errorMessage object from routes in a partial? I have attempted to implement it as shown below: Route:- const express = require("express"); const router = express.Router(); const Character = require("../models/character" ...

Having trouble getting my AngularJS directive with a number in the name to function properly

Check out my code snippet: app.directive('3dPlansSlider', function(){ return { controller: 'projectCtrl', restrict: 'E', templateUrl: 'views/3dPlansSlider.html', link: function(scope, element, attr ...

Serve different files using Node.js socket.io webserver, not just index.html

I recently started delving into socket.io and decided to use this chat example as a reference. As I navigate to ip:8080/public/index.html, I realize the need to access other files, such as additional JS scripts that will be used on the client side in the ...

JavaScript and PHP open-source libraries for enabling voice chat functionality

Seeking assistance on incorporating voice-chat functionality into my website through PHP and JavaScript. Are there any open-source libraries available for this purpose? I am willing to utilize Flash if necessary, but limited to using only Flash, JavaScri ...