4 ms·
Not really, at least as compared to ordinary pass-by-reference. Javascript, like Java, uses references for all objects, but passes by value. So the references a
by reissbaker 13y ago
Not really, at least as compared to ordinary pass-by-reference. Javascript, like Java, uses references for all objects, but passes by value. So the references are passed by value, but the objects themselves are passed by reference (since they're always references).
Passing references is quick, even by value: it's just passing around pointers. Here's basically how it would look in say, Go, with pointers:
package main
func main() {
var x = 10
test(&x)
println(x)
}
func test(ptr *int) {
var y = 30
ptr = &y
}
And the equivalent JS:
function main() {
var x = 10;
test(x);
console.log(x);
}
function test(ptr) {
var y = 30;
ptr = y;
}
// depending on environment, either call main() or run on onload or DOM ready
The main difference between the two is that in JS, x and y were already pointers; in Go, x is the actual value 10, and y is the actual value 30. However in both cases the test function takes a pointer that is itself passed by value.
The programs, naturally, both print 10 and not 30. The pointer was passed by value, and modifying the value of the pointer only changes the pointer, not the referenced variable. To change the referenced variable you'd have to dereference the pointer — and since JS doesn't provide access to raw pointers, that's impossible in JS. You can, however, mutate the variable using array accessors or dot notation; for example, in Go:
package main
type Vertex struct {
X, Y int
}
func main() {
var z = Vertex{X: 1, Y: 2}
println(z.X)
test(&z)
println(z.X)
}
func test(ptr *Vertex) {
ptr.X = 10
}
And once again the equivalent JS:
function main() {
var z = { X: 1, Y: 2 };
console.log(z.X);
test(z);
console.log(z.X);
}
function test(ptr) {
ptr.X = 10;
}
// depending on environment, either call main() or run on onload or DOM ready
As expected, the programs will first print 1, and then print 10.
As you can see, pass-by-value in JS is generally the same as pass-by-reference in other languages; it's all pointers under the hood.