Passing Variables by Reference in JavaScript
When performing multiple operations on variables within a loop, understanding how JavaScript handles variable passing is crucial. JavaScript, unlike many other programming languages, does not support passing by reference. However, referencing objects allows for the modification of their contents within functions.
function alterObject(obj) { obj.foo = "goodbye"; } var myObj = { foo: "hello world" }; alterObject(myObj); alert(myObj.foo); // "goodbye"
Iterating over arrays is also possible, allowing for the modification of each cell.
var arr = [1, 2, 3]; for (var i = 0; i < arr.length; i++) { arr[i] = arr[i] + 1; }
It's worth noting that true pass-by-reference involves the ability to modify values in the calling context, which JavaScript does not support.
function swap(a, b) { var tmp = a; a = b; b = tmp; } var x = 1, y = 2; swap(x, y); alert("x is " + x + ", y is " + y); // "x is 1, y is 2"
Unlike C , which allows for true pass-by-reference, JavaScript only supports passing references to objects. The modification of object contents within functions is possible, but references themselves cannot be modified.
The above is the detailed content of Does JavaScript Pass Variables by Reference or by Value?. For more information, please follow other related articles on the PHP Chinese website!