Refreshing the current variables within a JavaScript array

When I add variables to an array in JavaScript and then update each element, why do the variables all show the same value when outputting them in the console?

In this example, I would anticipate seeing 777 for all variables in the console, but instead they display as 0.

However, when logging the array itself, it correctly shows [777,777,777].

var number1 = 0;
var number2 = 0;
var number3 = 0;

var numbers = [number1, number2, number3];

function updateNumbers() {
  var i;
  for (i = 0; i < numbers.length; i++) {
    numbers[i] = 777;

    console.log(numbers);

    console.log(number1);
    console.log(number2);
    console.log(number3);
  }

}

updateNumbers();

Answer №1

When initializing your array, you are assigning the variables by value rather than by reference.

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

You can achieve similar functionality using objects instead.

var a = {
  value: 1
};
var b = {
  value: 2
};
var c = {
  value: 3
};

var test = [a, b, c];

function updateNumbers() {
  var i;
  for (i = 0; i < test.length; i++) {
    test[i].value = 777;
  }
}

updateNumbers();

console.log(test); // The output will be different from your initial example
console.log(a.value);
console.log(b.value);
console.log(c.value);

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

Transforming Ruby Arrays

I'm facing a challenge with a string of numbers: s = "12345678910" This sequence includes the numbers 1 through 10 in ascending order. My goal is to transform it into an array containing these individual numbers: a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ...

Obtaining input data from a form using Node.js

I'm facing an issue with my node.js app where the form data is not getting sent properly via POST request. I have tested the post endpoint using Postman and it works fine, but when I submit the form, the database receives an empty object without any o ...

Managing duplicate primary keys in JavaScript applications can be accomplished through various patterns and techniques

I am currently utilizing the npm sequelize library to manage storage utilizing MySQL. The primary key is the Task id, which is generated using the shortid library. What would be an effective Javascript pattern to handle duplicate ids in the rare case that ...

JavaScript: Adding up whole numbers--- Reference Error: Undefined

I'm having trouble with my code because it's saying that "t1" is not defined, even though it's the name of my text box. I tried making the variable global by declaring it outside the function, but it didn't solve the issue. Interestingl ...

Display one table when clicked and hide the others

Within the structure of my webpage, I have numerous tables that follow a similar format but contain distinct content. Initially, all these tables are hidden from view. My goal is to design a functionality where clicking on a specific button will unveil onl ...

Issue with toggling functionality on Material UI check boxes when they are printed in a loop

I am attempting to display checkboxes in rows of 4 dynamically, where the number of rows and checkbox values can vary. Below is my JSX code: matrix.map((row, index) => ( <TableRow key={index}> <TableCell al ...

Steps to incorporate iframe into a webpage with 100% height and enable page scrollbars

Looking to seamlessly integrate an iframe into a webpage? Here are the requirements: The iframe height must adjust to fit its content, occupying 100% of available space. Hide scrollbars within the iframe, allowing the page's scrollbars to adjust acc ...

Validating whether a condition aligns with any element within an array in JavaScript

Is there a better approach to determine if a condition matches any value in an array? For example, if I want to implement retry logic when receiving a 5xx error. var searchUserRequest = httpClient.request(searchUserRequestOptions, (res => { if(r ...

Develop a user authentication system using fundamental Python functionalities

As a novice, I am eager to create a password login system using Python. My goal is simple: if the correct pin is entered, it should display 'Login successful'. If an incorrect pin is entered, the user should be given 3 attempts before initiating ...

Tips for implementing ajax and codeigniter to load additional comments on a web page

Is it possible to customize Codeigniter's default pagination to achieve a "viewMore" link style when loading more records using AJAX? The challenge lies in creating a div that automatically expands to handle large numbers of records, such as 10,000 a ...

How do I retrieve URL GET parameters in the setup() function in Vue 3?

Here is the URL I am working with: http://localhost:8888/static/?foo=true, which my Vue 3 application relies on. Within the setup() function, I am aiming to retrieve the value of the foo parameter. This is the snippet of code I am using: import { useRout ...

Having trouble updating the state with an array of objects

Upon loading the component, I am attempting to set the state of an empty array with an array of objects. Despite trying various methods like using new ES6 syntax, mapping, joining, etc., I have been unsuccessful in getting it to work. When I inspect the ...

Every time I attempt to submit my text using AJAX, my div area ends up showing the existing data twice, along with the new data that

Hey there, I've got a script that retrieves JSON data for my chat application. The issue I'm facing is that it shows duplicate text - the one that was already posted and the new text from the database. Below is my entire JavaScript code: functi ...

Customizing the appearance of a Vue.js Single Page Application with

I have a custom-built Vue.js single page application and I am interested in implementing user-switchable dynamic themes. I envision a scenario where users can easily toggle between 'light' and 'dark' themes by clicking a button, and hav ...

In JavaScript, a "switch statement" retrieves a test value from a "input type text" by accessing the value using getElementByName.value

Attempting to test 7 possible values for the variable 'a' by passing it to a function from user input in seven 'input type text' boxes, then checking each value individually with clicks on 7 'input type image' elements. Howeve ...

Erase every picture contained within the element

<div id="uniqueidhere"> <span> <span><img src="image1link"></img></span> <span><img src="image2link"></img></span> <span><img src="image3link"></img></span> <span>&l ...

Modify the position of the CSS background for the Y-axis using jQuery

Let's consider a scenario with the following table: <table> <tr> <td class="t"></td> <td class="e"></td> <td class="s"></td> <td class="t"></td> </ ...

Utilizing NodeJS alongside Express to retrieve JSON response on the Client side

Currently, I am facing an issue with my Express server where I am struggling to properly read the information sent to the client as part of the response. One of the endpoints in my server is defined as follows: app.post('/click',(req, res) => ...

Having trouble performing an Image (base64) update in Next.js

Hi everyone, I'm facing a challenge with updating the image data in my code. The base64 string data updates correctly and the new image is displayed before submitting the data. However, once I submit the data, the image doesn't update. Below is ...

Identifying the relationship between child and parent components in Vue.js

I am new to Vue.js and I am practicing some simple exercises on communication between Vue components. However, I am struggling with understanding who is a child component and who is a parent component. For example, consider the following code snippet: HTM ...