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
Gabriel D. Celery
13,810 PointsHaving trouble understanding references in JavaScript
I am a little bit confused about how referencing works in JavaScript so I would appreciate it if someone could help me out on this one:
var myName = "Gabriel";
var yourName = myName
console.log(yourName) //This prints out "Gabriel" as expected
yourName = "Harry"
console.log(yourName) //This prints out "Harry" as expected
console.log(myName) //This prints out "Gabriel" as expected
Up until this point it does what I expect from the code, but this is where the confusion begins.
Problem 1:
var Harry = {
age: 32
};
var Mary = Harry;
Mary.age = 20;
console.log(Harry.age) //This prints out 20 instead of 32
And it doesn't end here.
Problem 2:
var arrayOne = [0,1,2,3];
var arrayTwo = [4,5,6,7];
arrayTwo = arrayOne
console.log(arrayTwo) //This prints out [0,1,2,3] as expected
arrayTwo[0] = 5;
console.log(arrayTwo) //This prints out [5,1,2,3] as expected
console.log(arrayOne) //But this also prints out [5,1,2,3] instead of [0,1,2,3]
So why are these things happening? I read it that it has something to do with references, but still couldn't find any clear answer. Can anyone explain it to me? Or is there a place where I can find a good material on this subject?
1 Answer
Jonathan Grieve
Treehouse Moderator 91,254 PointsThe thing with problem one is it looks like you're making Harry take on the properties of Mary, rather than having them exist as 2 separate objects
var Harry = {
age: 32
};
var Mary{
age = 20;
}
console.log(Harry.age);
console.log(Mary.age);
Again with problem 2 i think what's happening is you're overrrding one array so it takes on the values of another. So instead of having 2 arrays with the different values, both references will now show the same values. Even when you make an edit to one array index.
That's how I understand it, hope it helps :)