Friday, May 17, 2024
62
rated 0 times [  66] [ 4]  / answers: 1 / hits: 16478  / 11 Years ago, fri, july 26, 2013, 12:00:00

I have a question out of curiosity. So I looked into how JS handles variable assignment and I get it. How does variable assignment work in JavaScript?



But the same principle doesn't seem to exhibit itself in the following code I am working on:



var temp = playlist1[0];
playlist1[0] = playlist1[1];
playlist1[1] = temp;


I know this is a standard way to swap array elements. But if temp is pointing at playlist1[0], and playlist1[0]'s contents are changed to playlist1[1]'s then how come I don't end up with two playlist1[1] values in a row?


More From » pass-by-reference

 Answers
10

Not only variables are object pointers. All values (that are not primitives) are object pointers. So temp is an object pointer. playlist1 is a object pointer to an array object whose elements are object pointers. e.g. playlist1[0] is an object pointer, playlist1[1] is an object pointer, etc.




But if temp is pointing at playlist1[0]




This doesn't make sense. temp is an object pointer. It points to an object. playlist1[0] is not an object; it's an object pointer. temp = playlist1[0]; makes the object pointer temp point to the same object as object pointer playlist1[0].



If you know C, it is equivalent to something like this:



Object *playlist1[10];

Object *temp = playlist1[0];
playlist1[0] = playlist1[1];
playlist1[1] = temp;

[#76734] Thursday, July 25, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mustafaericho

Total Points: 322
Total Questions: 103
Total Answers: 110

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
mustafaericho questions
Mon, May 31, 21, 00:00, 3 Years ago
Sun, May 23, 21, 00:00, 3 Years ago
Sat, Feb 13, 21, 00:00, 3 Years ago
Sat, Jan 2, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
;