Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variables by reference in JavaScript

How do I pass variables by reference in JavaScript?

I have three variables that I want to perform several operations to, so I want to put them in a for loop and perform the operations to each one.

Pseudocode:

myArray = new Array(var1, var2, var3); for (var x = 0; x < myArray.length; x++){     // Do stuff to the array     makePretty(myArray[x]); } // Now do stuff to the updated variables 

What is the best way to do this?

like image 633
BFTrick Avatar asked Oct 12 '11 18:10

BFTrick


People also ask

Does JavaScript pass variables by reference or by value?

Javascript always pass by value so changing the value of the variable never changes the underlying primitive (String or number). However, when a variable refers to an object which includes array, the value is the reference to the object.

How do you reference a variable in JavaScript?

In JavaScript, it's just NOT possible to have a reference from one variable to another variable. And, only compound values (Object, Array) can be assigned by reference. Bottom line: The typeof value assigned to a variable decides whether the value is stored with assign-by-value or assign-by-reference.

Can you pass a variable by reference?

Pass by reference is something that C++ developers use to allow a function to modify a variable without having to create a copy of it. To pass a variable by reference, we have to declare function parameters as references and not normal variables.

What does pass-by-reference mean in JavaScript?

JavaScript pass-by-value or pass-by-reference It means that JavaScript copies the values of the variables into the function arguments. Any changes that you make to the arguments inside the function do not reflect the passing variables outside of the function.


2 Answers

There is no "pass by reference" available in JavaScript. You can pass an object (which is to say, you can pass-by-value a reference to an object) and then have a function modify the object contents:

function alterObject(obj) {   obj.foo = "goodbye"; }  var myObj = { foo: "hello world" };  alterObject(myObj);  alert(myObj.foo); // "goodbye" instead of "hello world" 

You can iterate over the properties of an array with a numeric index and modify each cell of the array, if you want.

var arr = [1, 2, 3];  for (var i = 0; i < arr.length; i++) {      arr[i] = arr[i] + 1;  } 

It's important to note that "pass-by-reference" is a very specific term. It does not mean simply that it's possible to pass a reference to a modifiable object. Instead, it means that it's possible to pass a simple variable in such a way as to allow a function to modify that value in the calling context. So:

 function swap(a, b) {    var tmp = a;    a = b;    b = tmp; //assign tmp to b  }   var x = 1, y = 2;  swap(x, y);   alert("x is " + x + ", y is " + y); // "x is 1, y is 2" 

In a language like C++, it's possible to do that because that language does (sort-of) have pass-by-reference.

edit — this recently (March 2015) blew up on Reddit again over a blog post similar to mine mentioned below, though in this case about Java. It occurred to me while reading the back-and-forth in the Reddit comments that a big part of the confusion stems from the unfortunate collision involving the word "reference". The terminology "pass by reference" and "pass by value" predates the concept of having "objects" to work with in programming languages. It's really not about objects at all; it's about function parameters, and specifically how function parameters are "connected" (or not) to the calling environment. In particular, note that in a true pass-by-reference language — one that does involve objects — one would still have the ability to modify object contents, and it would look pretty much exactly like it does in JavaScript. However, one would also be able to modify the object reference in the calling environment, and that's the key thing that you can't do in JavaScript. A pass-by-reference language would pass not the reference itself, but a reference to the reference.

edit — here is a blog post on the topic. (Note the comment to that post that explains that C++ doesn't really have pass-by-reference. That is true. What C++ does have, however, is the ability to create references to plain variables, either explicitly at the point of function invocation to create a pointer, or implicitly when calling functions whose argument type signature calls for that to be done. Those are the key things JavaScript doesn't support.)

like image 137
Pointy Avatar answered Sep 29 '22 10:09

Pointy


  1. Primitive type variables like strings and numbers are always passed by value.
  2. Arrays and Objects are passed by reference or by value based on these conditions:
  • if you are setting the value of an object or array it is Pass by Value.

     object1 = { prop: "car" };  array1 = [1,2,3]; 
  • if you are changing a property value of an object or array then it is Pass by Reference.

     object1.prop = "car";  array1[0] = 9; 

Code

function passVar(obj1, obj2, num) {     obj1.prop = "laptop"; // will CHANGE original     obj2 = { prop: "computer" }; //will NOT affect original     num = num + 1; // will NOT affect original }  var object1 = {     prop: "car" }; var object2 = {     prop: "bike" }; var number1 = 10;  passVar(object1, object2, number1); console.log(object1); // output: Object { prop: "laptop" } console.log(object2); // output: Object { prop: "bike" } console.log(number1); // ouput: 10
like image 26
Mukund Kumar Avatar answered Sep 29 '22 10:09

Mukund Kumar