DEV Community

Discussion on: JavaScript vs Java Pass by Value and Reference

Collapse
 
dubyabrian profile image
W. Brian Gourlie

Both Java and Javascript are strictly pass-by-value. There is an important distinction to be made when talking about "passing a reference" versus "passing by reference."

Actual pass by reference semantics are illustrated here (using c#):

static void Main()
{
    int foo = 123;
    AddOne(ref foo); 
    Debug.Assert(foo == 124);
}

static void AddOne(ref int i) 
{
    i += 1;
}
Enter fullscreen mode Exit fullscreen mode

As you can see, when passing by reference we are actually changing the value in-place, which is then reflected in the calling function. When passing an object by reference, it's even more apparent what's going on:

static void Main()
{
    Person p = new Person { Name = "William" };
    ChangePerson(ref p); 
    Debug.Assert(p.Name.Equals("Brian"));
}

static void ChangePerson(ref Person p) 
{
    p = new Person { Name = "Brian" };
}
Enter fullscreen mode Exit fullscreen mode

Note that we didn't just alter a property of the Person passed to ChangePerson, we changed p to point to a different object altogether, which is once again reflected in the calling function. None of the above is possible in Java or Javascript, because they are strictly pass-by-value.

The special sauce to really understanding this is realizing that a reference is a value type. So, when you call a function and pass an object to it, you're actually passing a copy of a reference to that object. The copied reference still points to the same object in memory, but if you change where that reference points to in the callee, it doesn't affect the calling function because they are distinct references. Again, using a similar example from above:

static void Main()
{
    Person p = new Person { Name = "William" };
    ChangePerson(p);

    // Unlike the example above, this assertion fails!
    // We passed a *copy* of the reference to ChangePerson, not the reference itself!
    Debug.Assert(p.Name.Equals("Brian"));
}

static void ChangePerson(Person p) 
{
    p = new Person { Name = "Brian" };
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tiffany profile image
tiff

Thanks for the explanation. Got it. Changed the article to reflect that.