re: Javascript uses call by sharing for objects VIEW POST

re: I'm still kinda confused. So if JavaScript uses pass by sharing, but pass by sharing resembles pass by reference, whats the difference? You ment...

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

const 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;


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;


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

code of conduct - report abuse