Are there pointers in javascript?
Asked Answered
D

7

84

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?

Deva answered 29/6, 2013 at 16:40 Comment(7)
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?Antoineantoinetta
Possible duplicate of Pointers in JavaScript?Cyaneous
@Antoineantoinetta To be honest I come here to find a way to write swap function like in C :)Kilometer
@EzioMercer: The idiom for that in JS is with destructuring: [a, b] = [b, a];Antoineantoinetta
@Antoineantoinetta It is true if a and b are references :) I mean you can't swap the values of primitives (for example numbers) in another function but you can do it easily in C with pointersKilometer
@EzioMercer: I’m saying without a function. Instead of writing swap(a, b), you [a, b] = [b, a]. (And no, the behaviour doesn’t depend on what a and b contain.)Antoineantoinetta
@Antoineantoinetta Sorry if I didn't express myself correctly. Yes, it is true that I can write [a, b] = [b, a] everywhere. I mean that I can't write this in a some function swap. For example in C it costs nothing to add additional log about swapping the values of two variables but in JS I have to write this additional log everywhere when I swap the values of two variablesKilometer
L
130

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
Litch answered 29/6, 2013 at 16:42 Comment(7)
What is a copy of a reference, can it be used like pointers and how do I use it?Deva
Reference is the name of the object, copy is basically a new name pointing to the same addressUniseptate
@user2297366 it's just a placeholder to represent the object's contents, as opposed to the reference to the object itself.Litch
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?Pinder
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.Pinder
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?Bahuvrihi
@Bahuvrihi I don't consider them to be analogous to pointers. 1) they're reference counted, 2) you can't do pointer arithmetic on them. NB: the OP specified C++, so there was no need for me to qualify that in my answer.Litch
G
66

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

Grosvenor answered 12/5, 2015 at 4:1 Comment(8)
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.Equanimity
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.Grosvenor
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).Equanimity
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.Grosvenor
@Grosvenor 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.Markmarkdown
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.Grosvenor
These are pseudo-pointers at best. You can't use them as object's keys which would be very helpful.Defy
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.Caddis
C
6

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.

Chellman answered 8/4, 2021 at 3:4 Comment(0)
I
3

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})
Itol answered 14/6, 2019 at 8:14 Comment(0)
F
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.

Fenner answered 12/5, 2022 at 8:31 Comment(0)
D
0

Yes, in fact, all objects and arrays are pointers. If I have to take your example literally, then, you only need to turn the variables to be of object types E.g.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pointers</title>
</head>
<body>
    <h1>Asynchronous JavaScript</h1>

<!--the pointer with class b--->
    <p>Our City</p>
    <p id="variableA" >Minnesota</p>

    <script src="pointers.js" ></script>
</body>
</html>

Then the pointers.js:

var a = {name: "todos", data: {pointerOne: 'Minnesota', pointerTwo: 'NewYork'}};
var b = a;//pointer to a

setTimeout(()=>{
//using timeout to see our pointer at work!

b.data.pointerOne = 'Nairobi';
document.getElementById('variableA').innerHTML = a.data.pointerOne;

}, 3000);

The major difference in JavaScript, is the way the pointers are actually presented or the lack of a direct way to identify pointers. In C, Golang, and C# pointers are made using the ‘&’ operator.

This is the basic. After getting this concept, you can now develop it further into function pointers, linked lists, or use it like structs; and do JavaScript the C++ way. Though I would advice you to use the current JavaScript convention in naming your variables. i.e

const a = {name: "todos", data: {pointerOne: 'Minnesota', pointerTwo: 'NewYork'}};
const b = a;//pointer to a
Dhobi answered 13/11, 2023 at 7:22 Comment(0)
S
-9

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
Screening answered 27/5, 2016 at 18:34 Comment(2)
You just return the properties of the car. It has nothing to do with pointers or imitating and is known as the scopeBrittaney
Technically JS is nothing but pointers. However you can only deref them and not manipulate the pointers themselves.Peckham

© 2022 - 2024 — McMap. All rights reserved.