81

I used C++ before and I realized that pointers were very helpful. Is there anything in javascript that acts like a pointer? Does javascript have pointers? I like to use pointers when I want to use something like:

var a = 1;
var b = "a";
document.getElementById(/* value pointed by b */).innerHTML="Pointers";

I know that this is an extremely simple example and I could just use a, but there are several more complex examples where I would find pointers very useful. Any ideas?

Dylan Vander Berg
  • 1,809
  • 1
  • 22
  • 37
  • 6
    Mmh… you shouldn’t generally need pointers. Can you give a more real-world example of a case you’ve encountered where pointers would be helpful? – Ry- Jun 29 '13 at 16:48
  • Possible duplicate of [Pointers in JavaScript?](http://stackoverflow.com/questions/10231868/pointers-in-javascript) – Dan Dascalescu Sep 14 '16 at 00:45

6 Answers6

125

No, JS doesn't have pointers.

Objects are passed around by passing a copy of a reference. The programmer cannot access any C-like "value" representing the address of an object.

Within a function, one may change the contents of a passed object via that reference, but you cannot modify the reference that the caller had because your reference is only a copy:

var foo = {'bar': 1};

function tryToMungeReference(obj) {
    obj = {'bar': 2};  // won't change caller's object
}

function mungeContents(obj) {
    obj.bar = 2;       // changes _contents_ of caller's object
}

tryToMungeReference(foo);
foo.bar === 1;   // true - foo still references original object

mungeContents(foo);
foo.bar === 2;  // true - object referenced by foo has been modified
Community
  • 1
  • 1
Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • 1
    What is a _copy of a reference_, can it be used like pointers and how do I use it? – Dylan Vander Berg Jun 29 '13 at 16:43
  • 3
    Reference is the name of the object, copy is basically a new name pointing to the same address – Mataniko Jun 29 '13 at 16:46
  • @user2297366 it's just a placeholder to represent the object's _contents_, as opposed to the reference to the object itself. – Alnitak Jun 29 '13 at 16:50
  • How much memory does a "copy of a reference" take up? Is it basically just an address of where to find the actual object or does it literally allocate another space in memory to copy the object to? – Frank Feb 03 '21 at 19:28
  • I assume that in: `var a = {}; var b = { c:a };` it is safe to say that `b.c` does not hold a copy of `a`, but a value representing the location of `a` in memory. In this case there would be 3 spaces allocated in memory: one for `a` of type Object, one for `b` of type Object, and one for `b.c` of type Int holding a value of the location in memory of `a`. – Frank Feb 03 '21 at 19:39
  • 1
    even though objects are passed around by passing a copy of a reference, wouldn't it still be considered a pointer? Not a pointer in the sense that we have direct access to it but a pointer in the sense that it is _a reference to the memory location of an object_, which JavaScript does have. Maybe a better way to rephrase your first sentence is instead of "No, JS doesn't have pointers", maybe something like "No, JS doesn't have C-like pointers". Because technically, objects are still pointers in JS. And what about Function Pointers/References? – Aeternus Apr 25 '23 at 00:03
62

You bet there are pointers in JavaScript; objects are pointers.

//this will make object1 point to the memory location that object2 is pointing at
object1 = object2;

//this will make object2 point to the memory location that object1 is pointing at 
function myfunc(object2){}
myfunc(object1);

If a memory location is no longer pointed at, the data there will be lost.

Unlike in C, you can't see the actual address of the pointer nor the actual value of the pointer, you can only dereference it (get the value at the address it points to.)

user3015682
  • 1,215
  • 12
  • 13
  • The 1st part works 100%. The var object1 is only pointing to object2. If we change object1, object2 changes actually. Changing object2 directly also nicely shows when we check the contents of object1. It will show that object1 is also changed BECAUSE IT POINTS TO THE SAME DATA IN MEMORY. I have tested this. I don't understand the 2nd part but it does not matter. – Tyler May 27 '19 at 23:39
  • 1
    Javascript is kind of funny about passing objects to functions. If the function alters one member of an object at a time it is pass by reference. However If you attempt to change the object completely using curly braces, it seems to pass by value. I'm guessing that this is because Javascript automatically thinks you're creating a new object when you do = {...}, basically making a local variable that happens to have the same name as the parameter. – user3015682 May 29 '19 at 06:22
  • 1
    It's actually not about creating a new object, as you explicitly say. I learned it's about passing the reference always: when you do objX = {..} you actually pass the reference to a newly created object. When you do objX = objY, then you pass the reference to an objY object which already existed. But the = actually always passed the address where the object on the right of assignment operator resides (does not matter whether it is newly created or an already existing one - the right side of the assignment operator resolves first). – Tyler May 30 '19 at 07:46
  • Good point! After some testing I've learned more, it is in fact always pass by reference, just be careful not to change it's address. – user3015682 May 31 '19 at 01:59
  • 5
    @user3015682 No, JavaScript is pass by value, not pass by reference. JavaScript does, under the hood, have "pointers." Pointers are simply variables that store the address of an object. They are passed by value. So you can modify the object being pointed to, but you can't force the object to point to something else by passing it to a function. – Aleksandr Hovhannisyan Feb 06 '20 at 11:58
  • Ya sure, everything is pass by value. It just so happens that the value being passed is the address of the object being passed. I suppose it would be more accurate to say reference variable, which is sort of like a constant pointer. – user3015682 Feb 07 '20 at 12:29
  • These are pseudo-pointers at best. You can't use them as object's keys which would be very helpful. – Eggon Feb 17 '22 at 12:14
  • Many people seem to confuse the concepts of pointers and references. References are just aliases of the same memory address. Pointers are variables that hold the memory address (or some similar identifier) of the actual object. Even if you can't explicitly access the address/identifier stored in pointers doesn't mean they aren't pointers. – tweekz Aug 10 '22 at 20:53
5

I just did a bizarre thing that works out, too.

Instead of passing a pointer, pass a function that fills its argument into the target variable.

var myTarget;

class dial{
  constructor(target){
    this.target = target;
    this.target(99);
  }
}
var myDial = new dial((v)=>{myTarget = v;});

This may look a little wicked, but works just fine. In this example I created a generic dial, which can be assigned any target in form of this little function "(v)=>{target = v}". No idea how well it would do in terms of performance, but it acts beautifully.

Timur Baysal
  • 111
  • 2
  • 5
2

due to the nature of JS that passes objects by value (if referenced object is changed completely) or by reference (if field of the referenced object is changed) it is not possible to completely replace a referenced object.

However, let's use what is available: replacing single fields of referenced objects. By doing that, the following function allows to achieve what you are asking for:

function replaceReferencedObj(refObj, newObj) {
    let keysR = Object.keys(refObj);
    let keysN = Object.keys(newObj);
    for (let i = 0; i < keysR.length; i++) {
        delete refObj[keysR[i]];
    }
    for (let i = 0; i < keysN.length; i++) {
        refObj[keysN[i]] = newObj[keysN[i]];
    }
}

For the example given by user3015682 you would use this function as following:

replaceReferencedObj(foo, {'bar': 2})
Toshiro99
  • 21
  • 1
0

Assigning by reference and arrays.

let pizza = [4,4,4];
let kebab = pizza;  // both variables are references to shared value
kebab.push(4);
console.log(kebab); //[4,4,4,4]
console.log(pizza); //[4,4,4,4]

Since original value isn't modified no new reference is created.

kebab = [6,6,6,6];  // value is reassigned
console.log(kebab); //[6,6,6,6]
console.log(pizza); //[4,4,4,4]

When the compound value in a variable is reassigned, a new reference is created.

octo
  • 11
  • 1
  • 3
-8

Technically JS doesn't have pointers, but I discovered a way to imitate their behavior ;)

var car = {
    make: 'Tesla',
    nav: {
       lat: undefined,
       lng: undefined
    }
};

var coords: {
    center: {
       get lat() { return car.nav.lat; }, // pointer LOL
       get lng() { return car.nav.lng; }  // pointer LOL
    }   
};

car.nav.lat = 555;
car.nav.lng = 777;

console.log('*** coords: ', coords.center.lat); // 555
console.log('*** coords: ', coords.center.lng); // 777
Sam Araiza
  • 796
  • 8
  • 12
  • 8
    You just return the properties of the `car`. It has nothing to do with pointers or imitating and is known as the `scope` – Dimitri L. Sep 12 '17 at 15:34
  • 1
    Technically JS is nothing *but* pointers. However you can only deref them and not manipulate the pointers themselves. – RickyA Dec 23 '19 at 14:05