Differences between referencing and valuing in arrays in JavaScript

I have noticed an interesting behavior when passing arrays to functions by reference. Even after modifying the array inside a function, the changes do not reflect when logging the array outside the function. For example:

let arr = [1, 2];
console.log(arr); // Logs [1, 2]
add(arr, 3)
console.log(arr); // Logs [1, 2] again

function add(array, el)
{
    array = [el];
    console.log(array); // Logs [3]
}

The question arises: Why does the console.log after calling add display [1, 2] instead of [3] (the value of the el parameter)?

Answer №1

The array remains untouched.

Instead, you're updating the array variable (changing it from pointing to the old array to pointing to a new array).

To illustrate, if you wanted to actually modify the existing array:

let arr = [1, 2];
console.log(arr);
add(arr, 3)
console.log(arr);

function add(array, el) {
  array.length = 0;
  array.push(el);
  console.log(array);
}

Answer №2

It seems like there may be some confusion regarding the scope of the array.

When you pass an array into a function and assign that variable to something else, like in the example below:

function add(array, el)
{
  array = [el];
}

You are essentially just reassigning the variable and not actually modifying the array itself. If you want to modify the array, you should do something like this:

function add(array, el)
{
  array[0] = el; // changing the first element to 3
}

By doing this, you will see that the array gets updated with the first element set to 3. This is how array modification works in this context.

If you want to create an entirely new array, you can follow a similar approach as shown below:

arr = add(arr, 3);

function add(array, el)
{
  array = [el];
  return array;
}

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

Unable to add files to my JavaScript file

I recently integrated React into an existing project, following the guidelines outlined here: https://reactjs.org/docs/add-react-to-a-website.html. Now, I'm facing an issue where I am unable to import any files (both .js and .css) into my main compone ...

Issue with JQuery form submission causing controller method not to be executed

I am facing an issue with two click methods in my JavaScript code. Method 1 is successfully hitting the controller method, but when I try to trigger Method 2 by clicking on a button, it does not seem to call the controller. I have tried various solutions ...

React's useState Hook: Modifying Values

I just started learning about React and React hooks, and I'm trying to figure out how to reset the value in useState back to default when new filters are selected. const [apartments, setApartments] = React.useState([]) const [page, setPage] = React.us ...

The Ubuntu virtual machine hosted on Google Cloud is experiencing difficulties connecting through Node.js using an external IP address

const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); const app = express(); app.listen(3000, function(){ console.log('Server is now live on port 3000' ...

Is there a way to overlay a div on a particular line within a p element?

Within this paragraph lies a collection of text encapsulated by a < p > tag. When this content is displayed on the page, it spans across 5 lines. My objective is to creatively style and position a < div > tag in order to highlight a specific li ...

transform constant values into API requests using React

The sample dataset mentioned will be retrieved from a backend API call handled by Flask. The API has already been configured on the backend. const rows = [ { name: "XYZ", age: "12", email: "<a href="/cdn-cgi/l/emai ...

Loading content dynamically with AJAX and enabling smooth page scrolling

Looking for a solution to this issue. I have a button on my webpage that, when clicked, uses AJAX to load content into a "div" element below the button. Everything functions properly except for one problem - every time the button is pressed, the page scrol ...

Comparison between PHP's JSON parser and Javascript's JSON parser

Can anyone help me with this PHP serialize JSON encoding issue? json_encode(array('pattern' => '^(?:/?site/(?[\w\-]+))?(?:/?intl/(?[a-z]{2}(?:\-[a-z]{2})?)/?)?(/?(?.*))')); // output json: {"pattern":"^(?:\/?site ...

Tips for positioning a React component above another component

I am currently facing a challenge while working on a table with an expand more option to display additional details for each specific row. I have implemented a slider to facilitate the expansion of the table. Presently, my ExpandToggle component is embedde ...

What is the process for sending values to a component?

I am working with a component called MyComponent: export class MyComponent { @Input() active:boolean; constructor() { console.log(this.active); } } In this component, I have declared an Input, and I pass it in as follows: <mycomp ...

Field cannot be submitted without the required input after an Ajax request

I want to ensure that all my text/email input forms require a submission before you can "Submit" the email. Unfortunately, when using Ajax to prevent the page from refreshing after pressing the button, the required attribute does not function properly. T ...

The type 'number[]' is lacking the properties 0, 1, 2, and 3 found in the type '[number, number, number, number]'

type spacing = [number, number, number, number] interface ISpacingProps { defaultValue?: spacing className?: string disabled?: boolean min?: number max?: number onChange?: (value: number | string) => void } interface IFieldState { value: ...

Troubleshooting broken links on a multi-page website built with node.js and ejs

I am encountering some difficulties with my multi-page website created in node.js/ejs. I suspect that the issue lies within the routing mechanism, although I have double-checked my routes and they seem to be configured correctly. The problem arises when I ...

Filtering data from Arduino using web serial communication

My setup consists of an Arduino kit connected to a webserial API that sends data to an HTML div identified by the id 'target'. Currently, all the data is being logged into one stream despite having multiple dials and switches on the Arduino. Th ...

Reading a file with fs alters the visibility of a global array, rendering it inaccessible beyond its scope

There are two sections of code. The first one is called by the second to populate an array and write it into a file. async function timeSeries(obj) { data = [ { original_value: [] } ] //read file named as passed obj ...

Pressing the non-responsive button automatically chooses the following item

This example demonstrates how to create a disabled button: import { Grid, IconButton } from "@material-ui/core"; import ArrowBackIosIcon from "@material-ui/icons/ArrowBackIos"; export default function App() { const handleClick = (e) ...

Building Silent Authentication in React Native with the help of Auth0: A Step-by-Step Guide

I am currently working on my first React Native app, and I have integrated Auth0 for authentication purposes. My goal is to implement silent authentication using refresh tokens. So far, I have attempted to use the checkSession() method but encountered an ...

Looking for assistance with a simple Javascript program

My program needs to have a for loop and utilize existing input functions (name and number). Additionally, I need to calculate totals. Users should be able to CANCEL and proceed to doc.write where they can enter their name and number. Furthermore, users s ...

What is the best way to have various texts display after a certain number of clicks?

I am looking for a way to display different text based on the number of clicks within a certain class. For example, if the user clicks twice, the text displayed should be "You clicked two times", and this pattern continues until the fifth click, after whic ...

Retrieve the URL redirected by JavaScript without altering the current page using Selenium

Is there a way to extract the URL I am supposed to be redirected to upon clicking a button on a website, without actually being redirected? The button triggers a complex Javascript function and is not a simple hyperlink. click() method doesn't meet my ...