Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Variables as Object Pointers

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?

like image 866
nemo Avatar asked Jul 26 '13 03:07

nemo


People also ask

Are variables in JavaScript pointers?

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.

Why pointers are not used in JavaScript?

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.

Can we use a pointer as a variable?

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.

How are JavaScript variables stored in memory?

“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.


1 Answers

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;
like image 184
newacct Avatar answered Sep 24 '22 07:09

newacct