Why the value I pass to a function behaves like a pointer?

I have this function :

static calculatePrice(offer)
{
    if (typeof (offer.TakerGets || offer.taker_gets) == "string")
        offer.quality = 1 / offer.quality;

    return offer.quality / 1000000;
}

I don’t understand why the function modifies the value that I pass to it (this.book[currency][side][this.j[currency][side]]). It does not modify a copy but the original as if I had passed it a pointer.

>Solution :

When you pass an object into a function (or assign it from one variable to another), you’re passing a value that’s called an object reference, which tells JavaScript where the object is in memory. (Yes, it’s a bit like a pointer in some other languages.) You’re not passing in a copy of the object. So yes, the function can change the state of that object by modifying its properties, etc.

Let’s take a simpler example:

function example(arg) {
    arg.answer = 42;     // Modifies the state of the object
}

let obj = {};
example(obj);            // Passes a value to the function saying where the
                         // object is in memory
console.log(obj.answer); // 42

In that code, the example function can modify the properties of the object, because what was passed in is an object reference.

It’s important to note that JavaScript is still purely pass-by-value, it’s just that the value being passed is an object reference. What the example function can’t do is change the obj variable that was used in example(obj) by assigning a different object to arg (arg = someOtherObject.) Doing that only affects arg, not obj. (There’s no link from arg back to obj, they both just have the same value in them.)

Leave a Reply