Argument changing within function

This is a function that takes 3 arguments: two numbers and a 2D array.
At the beginning I set a new variable, newcid, to be equal to cid. I then add items to the subarrays in newcid just as a convenient place to store relevant information. However, somehow adding these items to newcid actually causes the same changes to occur in cid. Why is that happening? I make no edits to cid throughout the function, why is it changing with newcid?

function checkCashRegister(price, cash, cid) {
    let newcid = cid;
    let totalCash = 0;
    let values = [0.01,0.05,0.1,0.25,1,5,10,20,100];
    for (let i = 0; i < newcid.length; i++) {
        totalCash += newcid[i][1];
        newcid[i].push(Math.round(newcid[i][1] / values[names.indexOf(newcid[i][0])]));
    let change = cash - price;
    if (totalCash === change) {
        return {status: 'CLOSED', change: cid}
    }`Preformatted text`

let newcid = cid

So newcid is a copy of cid. That’s fine. But cid is a reference to an array. newcid is a reference that points to the same array. It still has exactly the same values. As in exactly the same ones: the values in the array haven’t been copied. You can make as many copies of the reference as you want, that reference will still be for the same collection of values stored in the same specific places in memory.

1 Like

It’s the same thing that is happening in this challenge:
Variables only hold one value, but arrays and objects are bigger than a single value, so when a variable points to an array or object, it is actually holding the place in your computer’s memory where the array/object is stored. This means that

this does not copy the array/object, only the location of the array/object.

Okay, that makes a lot of sense. Thanks for your help

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.