Dylan Vander Berg
Dylan Vander Berg

Reputation: 1879

Are there pointers in javascript?

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?

Upvotes: 88

Views: 154330

Answers (8)

sumanth.js
sumanth.js

Reputation: 414

JavaScript doesn't have traditional pointers like C or C++, but it does utilize references. Understand the difference:

Primitive Values (No Pointers)

let num1 = 89;
let num2 = num1;
console.log(num1); // 89
console.log(num2); // 89

num1 = 29;
console.log(num1); // 29
console.log(num2); // 89 (remains unchanged)

Object References (Similar to Pointers)

let obj1 = { value: 89 };
let obj2 = obj1;

console.log(obj1.value); // 89
console.log(obj2.value); // 89

obj1.value = 29;  // change the value of obj1

console.log(obj1.value); // 29
console.log(obj2.value); // 29 (both reference the same object)

Let's create another object and point the obj1 and obj2 to this object

let obj3 = { value: 48 };
obj2 = obj3;
obj1 = obj2;

console.log(obj1.value); // 48
console.log(obj2.value); // 48

Now { value: 29 } has no variable to access so it becomes garbage, and is cleaned up by JavaScript's Garbage Collection

Upvotes: 0

Adioz Daniel
Adioz Daniel

Reputation: 516

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

Upvotes: 1

octo
octo

Reputation: 11

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.

Upvotes: 0

Timur Baysal
Timur Baysal

Reputation: 151

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.

Upvotes: 6

Toshiro99
Toshiro99

Reputation: 31

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

Upvotes: 3

Alnitak
Alnitak

Reputation: 339816

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

Upvotes: 135

Sam Araiza
Sam Araiza

Reputation: 934

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

Upvotes: -9

user3015682
user3015682

Reputation: 1255

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

Upvotes: 66

Related Questions