In the world of coding, passing an array by reference may seem

Can you explain why console.log(a) and console.log(b) do not return the same result of [1, 2, 3, 4]?

function test(c, d) {
  c = [1, 2, 3, 4];
  d.push(4);
}

a = [1, 2, 3];
b = [1, 2, 3];
test(a, b);
console.log(a);
console.log(b);

Answer №1

By initializing a = [1, 2, 3, 4];, you are essentially reassigning the argument (local to the function) passed into the test function. This does not modify the original array a. As a result, the a inside now references a different array than the one outside.

However, when b.push(4) is executed, it directly alters the external b array.

function test(a, b) {
  a = [1, 2, 3, 4];
  b.push(4);
}

a = [1, 2, 3];
b = [1, 2, 3];
test(a, b);
console.log(a);
console.log(b);

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

Passing a variable as a property to a nested child component in Vue.js

I am curious about how to efficiently pass variables to nested components. Within my setup, I have a total of 3 components: Main Secondary Tertiary All of these components share a common variable (referred to as sharedVar). If I want to avoid using Vue ...

View Preview Image using the following image tag in JavaScript

I am trying to display an image preview using the img tag that is placed after my input field. Here is my HTML: <input name="image" type="file" id="uploadImage" onchange="PreviewImage(this);" /> ...

Retrieving DOM Element in Angular from Freshly Loaded Template

Recently starting my journey with Angular, I have encountered a challenge when trying to access the DOM from a newly loaded template. Let me explain what's going on - index.html <div class="template" ng-app="myApp" ng-controller="myController"> ...

Initiate the command with given parameters

Currently, I am utilizing a combination of React, Redux, Rxjs, typesafe-actions, and TypeScript to invoke an action with parameters. Here is my current code: Actions: import { createAsyncAction } from 'typesafe-actions'; import {ICats} from &ap ...

Tips on utilizing Sinon for mocking a function that triggers a REST request

I'm currently navigating my way through sinon and mocha, working on the code and test provided below. My goal is to test the findAll() method without triggering an http request. However, I've encountered an error with the current setup: [TypeErr ...

Extremely sluggish change identification in combination Angular application

We are encountering consistent issues with slow change detection in our hybrid AngularJS / Angular 8 app, especially when dealing with components from different versions of the framework. The problem seems to arise when using older AngularJS components wit ...

What is the best way to have two text-divs overlapping within a single wrapper div?

In a wrapper div, there are two inner divs with different text. The goal is to change the text on hover and position the second text div exactly where the first text div is. .wrapper { background: red; width: max-content; padding: 20px; } .text1 ...

Receive regular updates every week for an entire month using Javascript

How can I calculate the number of check-ins per week in a month using Javascript? I have been unable to find relevant code for this task. Specifically, I am interested in determining the total count of user check-ins on a weekly basis. For example, if a u ...

What advantages do constant variables offer when selecting DOM elements?

What is the significance of declaring variables as constant when selecting elements from the DOM? Many developers and tutorials often use const form = document.querySelector('form'); ...

Reduce the occurrences of mouseover events being triggered

Is there a way to reduce the number of mouse over events triggered? I want to maintain the functionality of mouse over, but with fewer event triggers occurring. $(clientFrameWindow.document.body).on("mouseover",function () { //I am looking to slow down t ...

Issue with v-model not updating data correctly when using switch and select dropdown in VueJS

I am developing a dynamic admin panel that includes a CRUD generator using Laravel and Vue. Within my table, I am asynchronously loading data from an API. One specific column in the table, called is_featured, needs to function as a switch. This will allow ...

Interval function not initiating properly post bullet navigation activation

Currently, I am experiencing an issue with my custom slider where the auto sliding set interval function is not working after using the bullet navigation. Despite trying to implement "setTimeout(autoSlide, 1000);", it doesn't seem to be resolving the ...

Output a message to the Java console once my Selenium-created Javascript callback is triggered

My journey with Javascript has led me to mastering callback functions and grasping the concept of 'functional programming'. However, as a newcomer to the language, I struggle to test my syntax within my IntelliJ IDE. Specifically, I am working on ...

Is it recommended to rely on Javascript for altering the content of a div across an entire website?

I am in the process of creating my personal portfolio and have a few inquiries regarding the framework to implement. Currently, I have an index.html page that contains all the information I want displayed when visitors land on the site. Additionally, ther ...

Switching from hover to onload事件 in the JavaScript code

I am currently modifying some preexisting code to suit my requirements. https://tympanus.net/codrops/2010/02/08/awesome-css3-jquery-slide-out-button/ The sliding effect of the content when hovered with the mouse is what I am looking for. It seems straigh ...

Error: The module ./lib/helpers could not be located in NWJS

Whenever I attempt to run my application on NWJS, I encounter a problem. Upon checking the NWJS devtools console, I am presented with the error message Uncaught error: Cannot find module './lib/helpers/'. At the end of this particular line in the ...

Angular allows for dynamic sourcing of iframes

I have encountered an issue while trying to integrate a payment system with Angular. The payment gateway API I am using provides the 3D Secure Page as html within a JSON response. My approach is to display this html content within an iframe, however, the h ...

Tips for setting up listeners across multiple modules using socket.io

Last year, I created a multiplayer game using node.js and socket.io. Now, as part of my efforts to enhance the game, I am working on breaking down the code into modules. Currently, I am utilizing expressjs 4.4 along with socket.io 1.0. One challenge I enco ...

Error: Attempting to use Moment with Bootstrap Date Time Picker results in TypeError, as Object(...) is not recognized as

Let me show you the code for my picker in a simple way: import {moment} from 'moment'; const datePicker = () => { $('.datetimepicker').datetimepicker({ format: 'LT', locale: 'PT-BR', icons: { ...

The JavaScript code is attempting to execute a PHP script, however, I am struggling to parse the JSON data returned for use in the

As a novice, I am in the process of creating a JavaScript function that calls a PHP script every second. The PHP script retrieves values from MySQL DB, encodes them into JSON, which is then decoded by JS to display them on an HTML page. I have two queries ...