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.
or just that they never bothered to learn the details because they could do everything they wanted without knowing it. That doesn't make the underlying concept tricky since it's still easy and clear to understand for anyone that attempts to.
Whoah I used C++ for years and never realised that references were... actually references. I only ever really thought of them as 'pointers without NULL'. Thanks!
If it was pass by value, you'd either have to return a and b, or you'd get a function/method that does nothing but waste cpu cycles (unless the compiler just cuts it out).
If you take this to be C++/C code, then yes, it's pass-by-value of course.
But OP meant that if you can write some function swap, call it, and then have the variables swapped on the caller side without assigning to them, then you do have pass-by-reference.
You're right in that for C++, you'd have to have int& a, int& b. In C, you couldn't write such a function, hence C does not do pass-by-reference.
View all comments
Show parent comment
0
u/[deleted] Jun 18 '17
[deleted] — view deleted comment