Exploring the boundaries of arguments and object immutability in JavaScript

My recent assignment involves exploring scope and mutability concepts in JavaScript:

The task at hand is to create two functions, reverseArray and reverseArrayInPlace. The first function, reverseArray, takes an array as input and returns a new array with elements in reverse order. The second function, reverseArrayInPlace, should modify the original array to reverse its elements without using the built-in reverse method.

I successfully implemented the reverseArray function but encountered difficulties while working on the reverseArrayInPlace function. I tried multiple approaches, some of which failed, and now I'm looking for insights into why certain methods are unsuccessful. Although there are alternative ways to achieve the desired outcome, I am keen on understanding the behavior of my existing code.

// Function that reverses input array and outputs a NEW reversed array.
function reverseArray(myArray){
    var reversedArray = [];
    for(var i=0; i<myArray.length; i++){
        reversedArray.unshift(myArray[i]);
    }
    return reversedArray;
}

/*
    Reverse the original array in place
*/

// Approach 1: UNSUCCESSFUL
function reverseArrayInPlace1(myArray){
     myArray = reverseArray(myArray);
}

// Approach 2: UNSUCCESSFUL
function reverseArrayInPlace2(myArray){
    var original = [];
    for (var i=0; i<myArray.length; i++) {
        original[i]=myArray[i];
    }
     myArray = reverseArray(original);
}

// Approach 3: SUCCESSFUL
function reverseArrayInPlace3(myArray){
    var original = [];
    for (var i=0; i<myArray.length; i++) {
        original[i]=myArray[i];
    }
     var newArray = reverseArray(original);
     for (var i=0; i<myArray.length; i++) {
        myArray[i]=newArray[i];
    }
}

miArreglo = ["a", "b", "c", "d" ];
console.log("Original Array: ", miArreglo);

reversedArray=reverseArray(miArreglo);
console.log("Reversed using reverseArray function: ", reversedArray);

reverseArrayInPlace1(miArreglo);
console.log("Reversed using reverseArrayInPlace1 function: ", miArreglo);

reverseArrayInPlace2(miArreglo);
console.log("Reversed using reverseArrayInPlace2 function: ", miArreglo);

reverseArrayInPlace3(miArreglo);
console.log("Reversed using reverseArrayInPlace3 function: ", miArreglo);

Answer №1

The functions reverseArrayInPlace1 and reverseArrayInPlace2 are not functioning correctly due to the fact that arguments in JavaScript are passed by value. The variable myArray is local to the function, so reassigning it will not have any effect on the caller.

An alternative approach would be to create a new function called reverseArray that utilizes reverseArrayInPlace. This method would involve creating a copy of the input array using arr.slice(), reversing it in place, and returning the reversed array.

Answer №2

Your function contains a variable called `myArray` that points to the original array, allowing any changes made to its elements to directly affect the original array. For instance:

myArray[i] = x;

This means that modifications made to `myArray` will reflect on the original array. However, if you assign a new value to the `myArray` variable, it creates a local scope and only affects this specific variable. Check out @dwickern's answer for guidance on resolving your code.

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

Error: The 'length' property of the twitter object is not defined and cannot be read

I am trying to fetch data from my Twitter account using PHP and JSON. My PHP code is working fine, but I am facing an error with jQuery. Uncaught TypeError: Cannot read property 'length' of undefined $(document).ready(function() { var dm ...

What is the process for executing a Node.js file using a JavaScript command?

Currently, I am in the process of developing an online game that doesn't require high-speed interaction, allowing for the utilization of a single json file. My familiarity with node.js is limited, as I am relatively new to it. In my exploration, I ca ...

No results found for the regex pattern

In the code below, I have implemented a regular expression to detect URLs in a string and convert them into hyperlinks: <body> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunct ...

Reduce two array fields conditionally in a MongoDB aggregation pipeline

I've got a dataset that resembles the following: { "_id": 1, "user": "abc", "sentence": "I like to read books.", "nouns": [ "books" ], "verbs": [ "read" ] }, { "_id": 2, "user": "abc", "sentence": "Reading is my favorite h ...

Set a variable to contain a specific scope in JavaScript

I'm struggling to pass user input from a text box stored in $scope to a firebase query. Here's the code I have so far: $scope.array = []; $scope.addListItem = function(quote){ $scope.array.unshift(quote); console.log(quote) this.customQuote = ...

Guide to encoding an object containing multiple arrays of objects into JSON using PHP

My goal is to generate a JSON structure as shown below: { "success":[{ "success": "1" }], "friends": [ { "name": "ali", "phone": "934453" }, { "name": "reza", "pho ...

Please define a unique "redirect_uri" in the FB.ui() function for posting purposes

I'm currently utilizing the "Facebook Javascript Sdk" to publish messages on a user's wall. However, I am facing an issue with dynamic redirect URLs. Even though I am explicitly passing the "redirect_uri" as a link with query string in the FB.ui ...

How can I add text to a textbox within a duplicated div using Javascript or Jquery?

I'm looking to add text to a cloned div's text box using jQuery. I have a div with a button and text box, and by cloning it, I want to dynamically insert text into the new div. $(document).ready(function () { $("#click").click(function () { ...

When using AngularJS and Require together, there may be instances where the r.js

There seems to be a ongoing discussion about whether or not to use require.js with AngularJS, however, I have decided to implement it in my project. Currently, the project is set up and running with require, and my next step is to optimize and minify using ...

"Integrating a typeface.json font file into your three.js project: A step-by

I'm looking to incorporate 3D text into my website using the following code (reference: Labelling the vertices in AxisHelper of THREE.js): var textGeo = new THREE.TextGeometry('Test', { size: 10, height: 5, ...

The DOM assigned a new source to an image

Currently, I am working on a project that involves both jquery and PHP. In this project, users are able to upload images which are then displayed in blocks. The uploading functionality is already working, but I am facing an issue with setting the image sou ...

Explore the wonders of generating number permutations using JavaScript recursion!

After providing the input of 85 to this function, I noticed that it only returns 85. I am confused as to why it is not recursively calling itself again with 5 as the first number. console.log(PermutationStep(85)); function PermutationStep(num) { var ...

Developing a NestJs application using mongoose where collection names are dynamically generated

My goal is to dynamically change collection names based on the current year. For instance, from 'products' to 'products2020'. When using NESTJS, I need to import "module.forFeature" with a specific collection name. import { Module } f ...

issue retrieving data from live website created with next.js

Hello, I've exhausted all possible avenues to identify the cause of the error occurring on my live website built with NEXTJS. I have observed that this error only occurs when I reload the website. It's worth noting that I can successfully login ...

Combining Google Calendar authentication with FullCalendar integration

I recently started using the gcal example with full calendar from this source: https://fullcalendar.io/js/fullcalendar-3.8.0/demos/gcal.html. To authenticate, we are passing our calendar API and calendar ID, which is working well. However, I am worried ...

Attempting to grasp the concept of incorporating functional mixins

Here's my calculator function: var MyCalculator = function(c, d) { this.addition = function(c, d) { return c + d; }; this.multiply = function(c, d) { return d * c; }; this.subtraction = function(c, d) { return c - d; }; this.division = fu ...

Incomplete data retrieval issue encountered during .ajax call

I am having trouble retrieving all 4 key|value pairs from a page that displays an object as text in the body and pre tag. It seems to be missing one pair - any ideas why? Just a heads up, I've tweaked some of the URLs and data in the JSON output for ...

Ways to determine the numerical value of a specific word chosen by a user

I'm struggling to retrieve the position number of a word selected by a user. For instance If I have a simple paragraph with two words: Hi and Bob <p>Hi Bob</p> Therefore, logically Hi=1 and Bob=2. Now, if the user selects Bob, I want t ...

Leverage node rework CSS directly within your browser for seamless website

Looking to utilize the reworkcss/css library in the browser. Downloaded version 2.0.0 from GitHub and installed necessary packages with npm install. Attempted using requireJS, which supports processing the CommonJS Module Format by requiring index.js, bu ...

Arranging a collection of structures using qsort

I am currently developing a program to organize a "bigram array." This array consists of BigramObjects, each containing a "count" and a "bigram" value. My objective is to arrange the bigram array based on the "count" parameter. Below is the code snippet I ...