DEV Community

Discussion on: Copy by Value vs Reference

Collapse
 
parenttobias profile image
Toby Parent • Edited

The issue with the whole "pass by value" vs "pass by reference" thing is, javascript doesn't really do either. Well it does both. Well it does...

Javascript is consistent, both primitives and non-primitives work the same way. A string is passed the same way as an object, in large part. But the concepts of value or reference is fuzzy here, because any references are implicit, not explicit. We don't have pointers, so we aren't sharing a reference - but it seems we do, as arrays and objects are mutable from either side.

I think the best description I've seen for javascript's way of passing is Pass by share. When we pass something into a function, be it primitive or not, we are sharing the reference to that thing. We can't act on the reference, we can only follow it. In the case of primitive data types the value we reach is immutable, so any transformation becomes a new thing. But with non-primitive types, where mutation is possible, a shared reference becomes a little more problematic.

I've always seen the "Is javascript pass by reference or pass by value?" to be a trick question, for which there is no clean answer. It's the kind of a question, in an interview, intended to be wrong.

Edit for completeness: When I mentioned above "in large part*, it's because, internally, javascript does funky stuff with smallInt values, from what I've read. Rather than the variable referencing a lookup table, which referrences memory locations, which reference values? From what I've read, smallInt values are the only ones stored directly in the lookup table, and thus the only ones pass by value. What that means? Absolutely no idea. Still trying to test that, and see if it's relevant.

Collapse
 
aminmansuri profile image
hidden_dude

The true way to know if you're passing by reference in a language is this:

func f(ref val) {
val = newVal;
}

x = something
f(x)

If x is now equal to newVal then your language supports passing by reference (ex: in Pascal this works with var, or in C++ & notation). If x is still equal to "something" then I'm afraid you don't have true pass by reference.

Collapse
 
parenttobias profile image
Toby Parent

And that's why I suggest a different verb, pass by share. We are sharing that reference in an assignment to another variable, rather than passing the value itself. However the reference is tied to the immutable value, and not to the variable.

Javascript is weird, but once you grok, it actually makes a lot of sense.

Collapse
 
guillep2k profile image
Guillermo Prandi

That's a different discussion. The article is about assignments, not function calling.