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?
JavaScript variables are all implemented as pointers, and values are always on the heap, including primitive values and objects. (except for small integers due to pointer tagging) Objects are not passed by reference.
TL;DR: There are NO pointers in JavaScript and references work differently from what we would normally see in most other popular programming languages. In JavaScript, it's just NOT possible to have a reference from one variable to another variable. And, only compound values (Object, Array) can be assigned by reference.
A pointer variable (or pointer in short) is basically the same as the other variables, which can store a piece of data. Unlike normal variable which stores a value (such as an int, a double, a char), a pointer stores a memory address. Pointers must be declared before they can be used, just like a normal variable.
“Variables in JavaScript (and most other programming languages) are stored in two places: stack and heap. A stack is usually a continuous region of memory allocating local context for each executing function. Heap is a much larger region storing everything allocated dynamically.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With