Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Referencing variables and their values

Hi there to all.

I came to a point where I would need some ideas or maybe info on the matter of variable referencing.

I have 2 arrays of strings and I want to bind two index values together -> I want to change a value from Array A with a variable of Array B. The trick is that I don't want to overwrite the value.

A solution could be Array C where I save the relation between the two but I don't want to litter the back end with endless arrays.

Does anybody have an idea how to go about it?

Hey Nejc,

Can you post some code? I'm not sure what you mean by "binding" the index values. Or why Array A contains "values" and Array B contains "variables." If you would provide some example code, it would go a long way towards illustrating the particular problem you're facing and thus it would make it much easier for forum participants to understand and help you out.

1 Answer

One thing to consider is that array values are passed by reference... if you change a value in a or c, it changes for both of them:

var a = [1,2,3,4];
var b = a
a[0]=888;
b[3]=777;

console.log(a); 
//[ 888, 2, 3, 777 ]
console.log (b);
//[ 888, 2, 3, 777 ]

If you need to create a new array based on one of these arrays it is best to use .map, .forEach or a for loop to build a new array.

Alternatively, it actually seems like what you might want to use is a constructor function and create new instances of an object that stores the values you want, as you need them? https://css-tricks.com/understanding-javascript-constructors/