Home > Web Front-end > JS Tutorial > Does JavaScript Pass Variables by Reference or by Value?

Does JavaScript Pass Variables by Reference or by Value?

Barbara Streisand
Release: 2024-12-13 15:12:12
Original
699 people have browsed it

Does JavaScript Pass Variables by Reference or by Value?

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"
Copy after login

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;
}
Copy after login

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"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template