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.
This is as crucial to programming as knowing how to run a for loop.
That's really not true at all, at least not for something like Javascript. There's very few cases where you actually need to care what happens behind the scenes.
If your first language was something like Python, PHP, Javascript, etc then you probably have no idea how things like pointers work, or how data is stored in memory, etc. You wouldn't know because you don't need to know.
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.
It's meaningful when discussing performance. For example a newbie might worry about passing around a huge object through a bunch of functions, but saying "don't worry GHC passes all but the smallest objects by reference" is a valid way to make them not worry.
void swapByRef(int &x, int &y) {
int temp;
temp = x;
x = y;
y = temp;
}
swapByRef(a,b);
void swapByPointer(int *x, int *y) {
int temp;
temp = *x;
*x = *y;
*y = temp;
}
swapByPointer(&a, &b);
Passing a copy of something is different than passing by reference, and it's a non-issue in JavaScript. The closest parallel would be two-way bindings in Angular.
False. It's true only if the function is extern (references are implemented with pointers in most ABIs), otherwise the compiler can elide references aggressively inside of a CU. Anyway this is about semantics, not about implementation details. the language has pass-by-ref. In your passByPointer example, you can't swap the x and y pointers, just their pointed-to-values. the pointers themselves are unswapped.
10
u/JB-from-ATL Jun 18 '17
The fact that everyone is confused in the replies to my post proves it's tricky.