Why does javascript pass objects by reference?

I'm wondering if there is a rationale behind this, since it seems to me like it would be more object-oriented if objects were passed as values. Effectively it would be a function scope for Objects, like with primitives.

Is just for optimisation purposes that objects are passed by reference?


ref: http://snook.ca/archives/javascript/javascript_pass

Upvotes: 1

Views: 109

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276496

What are we passing by?

JavaScript does not pass objects by reference. It passes objects by reference values like C# and Java. JavaScript is always pass by value - that value might just happen to be a reference to an object.

function foo(obj){
   obj = {};
}
var o = {x: 5};
foo(o);
console.log(o.x); // 5, proof that JavaScript is pass-by-value

For example, in C++:

void foo(int& i){
    i = 5; 
}
int j = 10;
foo(j);
std::cout << j; // logs 5, this is what pass-by-reference is

Primitives in JavaScript are values, passing them by reference would be meaningless since by being values they're immutable anyway (you can't change the number 5).

But values have much better!

I agree, values have much nicer semantics. You can't return value that will be modified from an unknown location by mistake. It's a lot clearer and it turns out it's very easy to optimize. Immutability in general is gaining a lot of momentum in JavaScript and a lot of people (me included) are using immutable-collections (like ImmutableJS). Note that non-primitive value types are planned but are currently under specification and won't arrive before ES7.

This is the only reference I could find about it, I haven't seen it discussed in the discussion mailing list but I hope it's on the way :)

Basically, the understanding that we can do this efficiently is much newer than JavaScript. JavaScript is a really fun language but remember it was designed in 10 days by a single guy in urgency. The good stuff like value objects is on its way but we'll have to do with what we have right now. If it makes you feel any better a lot of other languages do this too (like Scala, Java and C#).

Upvotes: 3

Related Questions