4 ms·
It doesn't help us understand the language if we try to shoehorn JavaScript's behavior into one of two buckets: "pass by value" or "pass by reference." As you
by Stratoscope 9y ago
It doesn't help us understand the language if we try to shoehorn JavaScript's behavior into one of two buckets: "pass by value" or "pass by reference."
As you mentioned elsewhere, these terms are well defined in computer science. But how JavaScript works doesn't match either of them.
It only creates confusion to force JavaScript assignment and parameter passing into one of those two categories. This is what has led to the widespread misconception that "primitives are passed by value, and objects are passed by reference."
We're not implementing JavaScript engines here, we're programming in JavaScript. Implementation details like addresses and pointers are unknown to our code. They may differ from one JavaScript engine to another, and even during a single run of your program as the engine decides on the fly how to optimize or de-optimize your code.
What matters is the observable behavior from the point of view of the running JavaScript code.
There are a few ways you could describe that behavior, such as my notion of a new "name" that refers to an existing "thing", or shkkmo's and
andrewstuart2's "pass a reference by value". But it's not "pass by value" as that term is understood in other programming languages such as C/C++.
- BeeOnRope 9y agoIt's essentially exactly analogous to pass-by-value in C, where references are replaced by pointers. The primary difference is that JavaScript (and many other langues) use references as the only way to refer to an object, whereas C also has the concept of directly referring to an object by value where assignment or passing as a parameter will make a copy of the object.
- pjmlp 9y agoNo, JavaScript only does pass by value, nothing else. There is nothing to discuss here other than JavaScript developers trying to imagine stuff instead of learning the underlying literature concepts. JavaScript is not a special snowflake language. Computer Science describes how things are supposed to be, they don't change because of language X or Y.
- fleitz 9y agocomputer science defines some theories about how things should be... The actual science are the tests we write to find out how an API / etc actually works. Eg. Computer science says Spectre / meltdown don’t happen because the x86 spec says it doesn’t happen, however by practicing computer science we found out that it actually does happen.