The utilization of array.shift() alters the incorrect variable

It seems like I might be making a simple mistake here. Essentially, I have an array that I am passing into a function. My goal is to remove one element from the array, perform certain operations on it, and then iterate through the remaining elements of the array until there are none left. Once the array is empty, I want to go back and start over with the original array.

However, I'm encountering a strange issue when using array.shift(). It appears to be affecting the wrong variable, if that even makes sense.

Let me provide an abstract example:

var originalArray = [1,2,3,4,5,6,7,8,9]
  function goThroughArray(array){
      var untouchedArray = array
      console.log('untouched array before is ' + untouchedArray)

      var insideArray = untouchedArray
      console.log('inside array is ' + insideArray)

      var removedNumber = insideArray.shift()
      console.log('removed number: ' + removedNumber + ' from insideArray')

      console.log('inside array after is ' + insideArray)
      console.log('untouched array after is ' + untouchedArray)
  }

goThroughArray(originalArray)

The console log output shows:

untouched array before is 1,2,3,4,5,6,7,8,9
inside array is 1,2,3,4,5,6,7,8,9
removed number: 1 from insideArray
inside array after is 2,3,4,5,6,7,8,9
untouched array after is 2,3,4,5,6,7,8,9

This is all happening without any looping involved. Can anyone clarify why calling shift() on insideArray also affects untouchedArray?

I would anticipate that only the first element of insideArray, stored as "removedNumber", would be removed. So why does untouchedArray lose its first element too?

EDIT

    function addOne(number){
            console.log('number in is: '+number)
            var original = number;
            var modified = original
            console.log('original before is ' + original)
            console.log('modified before is ' + modified)
            modified++
            console.log('original after is ' + original)
            console.log('modified after is ' + modified)

        }

        addOne(1)

The output is:

number in is: 1
original before is 1
modified before is 1
original after is 1
modified after is 2

NEW EDIT

Even though this question is quite old, I wanted to update it with a simpler solution:

JSON.parse(JSON.stringify(obj))

This will create a copy of the object.

Answer №1

When working with Javascript, it's important to note that objects are never copied. For instance, if you have:

var a = [1, 2, 3, 4];
var b = a;

both a and b simply reference the same array object. So, any changes made to a will also affect b.

However, copies seem to be created with immutable types like numbers or strings:

var a = 14;
var b = a;
b = b + 3;
console.log(a); // outputs 14

This is because the + operator returns a new number object, binding b to this new value instead of the original one.

If you do need to make a copy, you must do so explicitly. For arrays, you can use the slice method without parameters:

var b = a.slice(); // Creates a new independent copy of the array

Answer №2

When working with JavaScript, assignments are carried out by value:

var x = 1,
    y = x; // 1 (assigned by value)
x = 2;
y; // 1 (remains unchanged)

However, for objects, the assigned value is actually a reference in memory. This implies that any modification made to an object's property will be reflected in all variables pointing to that object:

var objA = {},
    objB = objA;

objA.name = 'John';
objB.name; // 'John' (change seen across both variables)

objA = {}; // Yet, if you replace the entire object, the change won't propagate because assignments are done by value
objA.name; // undefined
objB.name; // 'John'

Answer №3

When it comes to JavaScript, it operates as a pass by value language. To delve deeper into this concept, you can refer to this insightful article or simply search for more details on Google.

If you encounter a situation where you need to make changes without affecting the original array, it is advisable to create a clone of your array.

One way to achieve this is by executing the following code snippet:

let clonedArray = originalArray.slice();

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

Image Placement Based on Coordinates in a Graphic Display

Placing dots on a map one by one using CSS positions stored in arrays. var postop =[{'top':'23'},{'top':'84'},{'top':'54'},{'top':'76'},{'top':'103'}]; var ...

How can I use query to swap out elements within a div when clicked?

I have a project with two separate div classes named demo-heart and demo-coal. The goal is to implement functionality that allows the user to click on the fa-heart icon and have it switch to fa-coal, and vice versa when clicking on fa-coal. <div class ...

Leveraging an array of Elasticsearch documents using AngularJS

The query results are given below... { "took": 6, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 45, "max_score": 0, "hits": [] }, "aggregations": { ...

Adding a custom class to the body element for specific routes in Next.js can be achieved by utilizing the features of

I am looking to apply my custom class to certain pages, with the exception of specific routes. For example, all pages should have the class fixed-header, except for the following routes: /cart/step-1 /login This class should be added or removed from the ...

Remove the underline from links in gatsbyjs

When comparing the links on (check source code https://github.com/gatsbyjs/gatsby/tree/master/examples/using-remark), they appear without an underline. However, on my blog (source code here: https://github.com/YikSanChan/yiksanchan.com), all links are un ...

Turn off Typewatch binding upon pressing the Enter key

I have integrated the Typewatch jQuery plugin into my application and below is the code snippet used for form submission and Ajax request handling. searchForm.on('submit', function(event) { if (event) { event.preventDefault(); } ...

Encountering a problem with CORS in the jQuery API while trying to

Currently, I am initiating an API request from a separate domain. There is currently no authorization check in place, however, we are considering implementing one in the future. When I make a request to this API without any headers, I receive a response. ...

What is the best way to filter an array of objects using an array of strings?

Suppose we have an array filled with objects : people = [ {id: "1", name: "abc", gender: "m", age:"15", country:"USA" }, {id: "2", name: "def", gender: "m", age:"2 ...

Utilizing a V-for/V-if loop to iterate through a multi-dimensional array and filter data based on date

I'm facing a challenge with setting up a v-for loop for an array I've constructed, which is already in the desired format Below is a snippet representing the data format. Essentially, I want to create a table for employees where the header consi ...

How to access v-model from a separate component in Vue.js

How can I access a v-model that is located in a different component? The search field is within the App.vue file and I am trying to activate the :search='search' property in the Datatable.vue component. Code in App.vue: <v-text-field ...

How is the purpose of nesting functions within functions achieved in nodejs?

Take a look at this example: var tools1 = require('../tools/tools1'); var test_func = function(arg1, arg2, arg3) { var local_var_1 = "lc1"; var local_var_2 = "lc2"; return function(data) { var result = tools1.doSth(local_va ...

Why using document ready is ineffective for handling kendo controls

Feel free to test out the code snippet below: <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="http://cdn.kendostatic.com/2014.2.1008/js/kendo.all.min.js"></script> <script type="text/javascript"& ...

Elements in ExtJS Tree panel not displaying properly

I am currently working on a tree panel that displays data from a JSON file. When I expand one category, the elements display correctly. However, when I expand another category, the previously opened elements disappear. This issue persists with all elements ...

"Quick as a keypress, the pace at which we move

Trying to explain my issue as clearly as possible. I have a Pacman game where the player controls Pacman using the keyboard. Pacman moves a constant unit in each direction and collision detection is based on a predefined map with obstacles marked by "-". ...

Is it possible to invoke a Javascript function from a coffeescript file?

Struggling to invoke a javascript function from a Coffeescript file within my $(document).ready(), but it seems like the function is not being executed. The function I intend to call originates from an external source that I have included in the head sect ...

PHP scripts for performing multiplication and subtraction operations

My goal is to create a PHP script that can determine the total miles driven by a car rental customer (at a rate of 0.12 cents per mile), calculate the cost based on the number of days they rented the car ($15 per day), and display the grand total in a text ...

Retrieving data from a jstl input field using jQuery

In my current project during the spring season, I am utilizing jstl and jQuery. Within a JSP page, there is a text field as follows - <form:input path="suv.userName" cssClass="textField" placeholder="Username (Email-Id)"/> The issue arises when at ...

Issue encountered while attempting to load external JSON file from server in AngularJS

Currently, I am attempting to load a JSON file from the server. Below is my services.js file: angular.module('starter.services', []) /** * A simple example service that returns some data. */ .factory('Friends', function($http) { ...

A method to access the key value of an array element that satisfies a given condition within a for loop

I have an array containing keys and values, and I need to extract the value associated with a specific key. Currently, when I run this code, it only returns the value of the last key in the array. I am open to modifying the structure of the array if neces ...

Leveraging angular.forEach for JSON Iteration

In my app and controller, I am working on creating a "flow chart style" question and answer system. To keep track of the current question and answer, I am using variables like $scope.ActiveQuestion and an array named $scope.ActiveAnswers. I am struggling ...