Can't find a problem 🤨

Greeting coders, I was scratching my head with my code until I found where things got messy. I am wondering why after “result[0][1] = 0” is my variable “curr” changing too. I am only changing one variable. Am I missing some information on arrays or…?

var curr = [
           ['PENNY', 0.01], 
           ['NICKEL', 0.05], 
           ['DIME', 0.1], 
           ['QUARTER', 0.25],
           ['ONE', 1],
           ['FIVE', 5],
           ['TEN', 10],
           ['TWENTY', 20],
           ['ONE HUNDRED', 100]];
  
var result = [];

  var a = curr[0];
  result.push(a);
  result[0][1] = 0;
  return  curr[0]; //returns ["Penny",0]

Thanks for helping out!

@davoska

@camperextraordinaire beat me to it as I was typing and he achieved a more clear explanation.
:sunglasses:

Arrays are really passed as pointers to an object.
You create an object curr (which is an array) when you declare the curr variable array.
You create an object result (which is an array) when you declare the result variable array.
You create a pointer to your curr object when you create variable a.
a and curr are one in the same, they are pointing to the same object (one being the object, the other being a replica of the object as a pointer, think of this as a reference or a “mask”)

Any changes to a will also change curr.
Any changes to curr will be reflecting in a when you view a value or property (its pointing to curr).

So when you put a into result, you are really putting a pointer to curr into result.
So when you reference result and make a change, you are changing curr directly, and when you call the pointer (which is a) those changes will be reflected.

You have created object1 (curr), a pointer to that object (a), and then stored the pointer (a) in another object2 (result). So when you work on result right now you are working on the pointer to curr which is a, which will in fact change curr as if you were calling it directly itself.

In essence curr, a, and result are the same in your code as you have set it up and used it.

Does this help?

-WWC

1 Like

Thank you for the visual edit and a brief, well-made explanation! I didn’t know that they are only references and not separate things. I’ll keep in mind the edit in the future!

Thank you as well! :sweat_smile:
We learn new things everyday, I didn’t know JS uses variables in this concept as pointers. Your explanation is great, thanks!