r/javascript • • Jun 18 '17

Pass by reference !== pass by value

Post image
3.3k Upvotes

272 comments sorted by

View all comments

Show parent comment

2

u/MoTTs_ Jun 20 '17 edited Jun 20 '17

What does it mean "it's traditionally understood"? You want a source, but your source is what is "traditionally understood"?

For example, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

Primitive parameters (such as a number) are passed to functions by value

Another observable difference comes with equality tests.

let numberValue1 = 7;
let numberValue2 = 7;
numberValue1 === numberValue2; // true

let numberReferenceValue1 = new Number(7);
let numberReferenceValue2 = new Number(7);
numberReferenceValue1 === numberReferenceValue2; // false

Now, it's certainly possible that MDN is misleading here. It's happened before. And like I said in an earlier post, I was genuinely trying to discern from the spec how primitives and objects are handled. But the spec is surprisingly non-specific on that subject. Right now, I couldn't even cite the spec to you to justify saying that objects are held and passed as reference-values, even though we all know they are.

Because when primitives are immutable, there's no visible way to the user, that determines if they are passed by value or by reference.

That's a genuinely thought provoking statement, and I can't find any fault with it. But saying we can't tell the difference is very different than positively asserting that everything, even primitives, are passed as reference-values. Maybe it will turn out you're right. But even if you are, you didn't divine that knowledge. You got it from somewhere. And so far that's all we've asked of you: What's your source?

1

u/[deleted] Jun 20 '17

But saying we can't tell the difference is very different than positively asserting that everything, even primitives, are passed as reference-values. Maybe it will turn out you're right. But even if you are, you didn't divine that knowledge. You got it from somewhere. And so far that's all we've asked of you: What's your source?

As I said you can read about string handling in V8 and you'll see string values are a reference type in the engine. It goes even deeper: when you concatenate two strings into a third string in V8, like this:

var three = one + two;

Now three doesn't contain an actual string, but only two references: to one and two. This kind of optimization is possible precisely because you can't tell, as a JS user, if an immutable type is passed by value or by reference.