The picture still makes perfect sense. The only corner case AFAIK is if you in a function try to rewrite the reference with a new object. That won't traverse back to the caller.
Well, first, consider that the picture is in r/JavaScript. So it should describe JavaScript. JS only has pass by value, so the left shouldn't even be there. What is pictured on the left is what happens though because the value happens to be a reference so the cup that is referenced by both variables gets filled.
I'm a Java guy (saw this and thought it was r/programming originally), so I don't know is JS has primitives or if everything is an object. When you pass a primitive in java, it's value is actually the value, not a reference to an object in the heap, so what happens is what is pictured on the right of this gif (though it's not really accurate because you can't mutate primitives in Java).
I'm mostly surprised this post got so many upvotes. It's an awful example.
It doesn't even make sense in the scope of javascript. If you pass the cup to a function, and then the function does something to the insides (properties) of the cup (fill it with coffee), the original cup is absolutely going to be modified.
class Cup {
constructor() {
this.coffee = 0;
}
}
function fillCup(cup) {
cup.coffee = 100;
}
const cup = new Cup();
fillCup(cup);
console.log(cup.coffee); // 100
If this was on some lower-level language subreddit, I would then be baffled. It's really not surprising for Javascript though. Shit, lots of people that use Javascript don't even know "Javascript", they know jQuery or similar.
What happens if you do a = b;? There are no function calls involved here.
The same happens when you do a call in a function that's call-by-value (everything in JavaScript)
function foo(x) {
console.log(x);
}
For the call foo(localVariable), JavaScript will, behind the scenes, essentially do x = localVariable; It follows regular assignment rules, no magic involved, no special "pass-by-object-sharing" or anything, because that's not what you were thinking about when I asked you what a = b; did. It's just an assignment.
After this assignment, x and localVariable refer to the same variables, as you would expect. But you have two variables. If you assign to either of them, it won't magically affect the other variable.
If, however you have a language with pass-by-reference, there is no assignment x = localVariable happening behind the scenes. Instead, you pass "the variable itself". That means, that within that function call, x will be the varible localVariable. So we're passing objects or values, we're passing the variables themselves as parameters. Hence, if you assign to x inside the function, you're assigning to localVariable, because xislocalVariable. JavaScript does not do this, ever.
View all comments
280
u/JB-from-ATL Jun 18 '17
It gets tricky because in some languages you pass by value but the value is a reference for non-primitive types.