DEV Community

Discussion on: Javascript uses call by sharing for objects

Collapse
 
bradtaniguchi profile image
Brad

I'm still kinda confused.

So if JavaScript uses pass by sharing, but pass by sharing resembles pass by reference, whats the difference?

You mention there is "copy" mechanism when passing the object to the function, which I guess becomes the new "reference" of the object?

Do you have an example where JavaScript would work differently if it uses pass by reference? Or is this all how the JS engine actually handles stuff under the hood?

Collapse
 
powerc9000 profile image
Clay Murray • Edited

Okay so when JS passes and argument to a function you get something like this

const bar = {};
foo(bar)

bar we can think of as a piece of paper saying where to find the data.
Then when we give bar to the function foo JavaScript photocopies that piece of paper and gives it to us. If we alter the paper it won't change anything about what's at bar's location. eg


function foo(bar){
//This will have no effect. Outside foo
bar = {};

}

But if we go to the address and make changes there other people can see it.

function foo(bar){
//This change is visible outside the function.
bar.something = "hello"
}

Now because we always make a photocopy no matter what we pass to a function, if we pass a number

const other = 2;

something(other);

This time it's like we wrote the number 2 on a paper other and then photocopy it and give it to something

If we change the number we are only changing our copy

function something(other){
    //Has no effect outside the function
    other = 2;
}

So if a language is pass by reference what are we doing? We are handing the function that same piece of paper and NOT making a copy of it. And when we are done we give it back to whoever called us. So any changes we make to the paper gets reflected outside the function.

PHP has this functionality

$foo = 2;

bar($foo);

//notice the &
function bar(&$foo){
    $foo = 3;
}

After we call bar in the PHP example $foo will be 3 for EVERYONE not just locally in the function bar.

Hopefully that makes sense.