Is it possible to assign a different array to a variable in JavaScript?

I'm facing an issue with manipulating arrays in JavaScript within a function. This problem arises from an exercise found in the book Eloquent JavaScript, focusing on two specific functions:

  • reverseArray(): designed to produce a new array that is the reverse of the original input array.
  • reverseArrayInPlace(): meant to reverse the original input array without creating a new one.

While attempting to implement the logic for reverseArrayInPlace(), I tried calling reverseArray() and reassigning its result back to the argument array. However, upon displaying the modified array, no changes were reflected. This was puzzling to me as I expected JavaScript arrays to be passed by reference.

Furthermore, I experimented with reassigning an array variable to another array successfully outside any function context. So, what could possibly be causing this discrepancy? It's worth mentioning that the exercise explicitly prohibits the use of the built-in reverse() method in JavaScript.

function reverseArray(array) {
  var new_array = [];
  for (var i = array.length-1; i >= 0; i--)
    new_array.push(array[i]);
  return new_array;
}

function reverseArrayInPlace(array) {
  array = reverseArray(array);
}

var r1 = [1,2,3,4,5,6,7,8,9,10];

console.log("r1 ", r1.join(",")); 
// → 1,2,3,4,5,6,7,8,9,10

console.log("reverse of r1 ", reverseArray(r1).join(","));
// → 10,9,8,7,6,5,4,3,2,1

console.log("r1 ", r1.join(","));
// → 1,2,3,4,5,6,7,8,9,10

reverseArrayInPlace(r1);
// the changes are not reflected here

console.log("r1 reversed in place ", r1.join(",")); 
// → still 1,2,3,4,5,6,7,8,9,10;
// this should display r1 = 10,9,8,7,6,5,4,3,2,1

Answer №1

The array variable in the function reverseArrayInPlace is confined to that specific function. Therefore, any assignment to it causes the scope to disregard the previous value, which was the array r1.

Take a look at this example :

var a = 5;
function change(a) {
  // Inner 'a'
  a = 0;
  console.log("inside change : ", a);
}

// Outer 'a'
change(a); // → 0
console.log("outside change : ", a); // → 5

You can observe that even though both the global scope and the scope of change function use the same name a, they are distinct variables. Modifying a within change will not impact the outer a.

HOWEVER
When dealing with an object (or any instance of Object.prototype, such as an array), modifying properties inside a function will alter them outside as well.

To grasp this concept fully, carefully examine the following :

var o = {
  arr1: [1, 2, 3],
  arr2: [1, 2, 3],
  str: "foo",
  num: 1
};

console.log("before changing : ", o);

function change(a) {
  // Updating properties of 'a'
  a.arr1[0] = 0;
  a.arr2 = ["destroyed"];
  a.str += " bar";
  a.num = a.num * 15;
  
  // Reassigning 'a'
  a = { change: "Destroyed !" };
  
  console.log("inside change : ", a);
}


change(o); // → { change: "Destroyed !" }
console.log("outside change : ", o); // → original 'o' with modified properties.

Even after assigning a = { change: "Destroyed !" };, there was no impact on o. However, all modifications made to the properties of o were reflected.

The end result of altering o is demonstrated below :

{
  arr1: [0, 1, 3],     // First item changed.
  arr2: ["destroyed"], // Completely new array created.
  str: "foo bar",      // Added " bar".
  num: 15              // Result of multiplication by 15.
}

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 transferring an array between two applications using AngularJS

I have two applications, appA for front end and appB for admin end. In appA, I am building an array called queries using a service through a controller. However, when I try to retrieve this array list in a controller in appB, it appears empty. Everytime ...

Tips for renaming input file before uploading to a new destination

Instead of using the original name, I would like to replace the image that the user wants to upload with my own pattern. I understand that it's preferable to change the file name on the server, but unfortunately, I am unable to do so for certain reaso ...

javascript dynamic content remains unaffected by ajax call

I'm a beginner with javascript and I am using a PHP variable to create links dynamically. Here is an example of how the variable is set: $addlink = '<button class="blueBtn btnSmall" id="current'.$product_id.'" onClick=addcart(' ...

Custom HTML form created by Ryan Fait with additional unique elements

My current script for styling checkboxes and radiobuttons is working perfectly: The issue arises when I dynamically add checkboxes and radiobuttons to the page using jQuery. The new elements do not inherit the custom styling. Is there a workaround for th ...

Displaying specific choices depending on the previous selection made

I am facing an issue in Laravel where I have two selection options, and one depends on the other. Despite multiple attempts, I haven't been able to resolve it. The database structure is as follows: companies id title channels id company_id title I ...

Access control using Vue.js Cookies

Within my current project, we have both superusers and staff members. The specific task of deleting users is reserved for the superuser role only. This leads me to question whether it is plausible to delete a user by utilizing cookies? ...

Importing three.js using ES6 syntax

When it comes to working with ES6, my workflow involves using Babel and babel-plugin-transform-es2015-modules-system.js specifically to transform module import/export for compatibility with system.js. I rely on a "green" browser for most ES6 features excep ...

Exploring the process of iterating through arrays within an object in vue.js using the v-for directive

Is there a way to iterate through an output object using the v-for template in Vue.js? new Vue({ el: app, data: { output: { player: [1, 5, 61, 98, 15, 315, 154, 65], monster: [14, 165, 113, 19, 22], }, }, }); <script src= ...

error: 1 exit status returned by the ld collector, reference undefined

New to the world of programming and facing a challenge. I'm stuck trying to compile this code, but keep encountering the following error: I suspect it may not be related to functions like insert_array_ascend, get_value, read_value, or is_in_array, bu ...

Using method as a filter in AngularJS: A guide to implementing custom filters

I've created a custom data type called Message: function Message(body, author, date) { this.body = body; this.author = author; this.date = date; this.stars = []; } Message.prototype.hasStars = function() { return this.stars.lengt ...

What is the process for transferring image attributes to the server via a URL?

My data transmission process only involves sending data. Below is the data I send: export const cabin = { name: '001', maxCapacity: 2, regularPrice: 250, discount: 0, image: './cabins/cabin-001.jpg', description: ...

I am unable to find any resolution, so to speak

Despite reading numerous posts and trying different examples on my own, I still can't grasp this particular question that has been asked many times before. My struggle lies in returning images from various folders and processing them individually in a ...

An element in defaultProps deemed as nonexistent

As I dive into routes and routing practice, I've encountered some challenges that have me stumped. The issue seems to be in the render method in App.js. The concept is simple - I'm working on a getDogFunc function that should help me locate a s ...

Tips for sending AngularJS expressions to a controller

I am looking to pass a value from an AngularJS Expression to the controller. Here is the HTML code : <div data-ng-controller="AlbumCtrl"> <div data-ng-repeat="z in songInfo"> <div data-ng-repeat="b in z.album& ...

Is there a way to position the menu above the button?

I need some help with my menu. Currently, it is showing up below the button and within my footer instead of above the content like I want it to. If anyone can assist me in understanding what I am doing wrong, I would greatly appreciate it. Thank you for ta ...

Using the $lookup aggregation stage to $group a nested array in MongoDB

I'm working with a Product Schema that is partially built using mongoose. Here's a snippet: attributes: [ { set: { ref: 'AttributeSet', type: Schema.Types.ObjectId }, items: [ ...

Obtaining your CSGO inventory via Steam API using jsonp: A step-by-step guide

Hey there! I'm currently facing an issue while trying to access a player's CSGO inventory using Valve's API. Unfortunately, I keep running into the error message stating that no 'access-control-allow-origin' header is present on th ...

Calculating the total price of items in a shopping cart by multiplying them with the quantity in Vue.js

I am currently working on enhancing the cart system in Vue.js, with a focus on displaying the total sum of product prices calculated by multiplying the price with the quantity. In my previous experience working with PHP, I achieved this calculation using ...

Starting your React application with the `npm start` command

After creating my react app using the create-react-app command, I named it react-app. These were the steps I followed: Navigate to the directory by typing cd react-app/ Run the command npm start Encountered an error message that reads; npm ERR! Missing ...

Stop the recurrence of multiple clicks by incorporating a Bootstrap modal popup confirmation

$('button[name="remove_levels"]').on('click', function (e) { var $form = $(this).closest('form'); e.preventDefault(); $('#confirm').modal({ backdrop: 'static', ...