Pass Variables by Reference in JavaScript

Pass variables by reference in JavaScript

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.)

Does JavaScript pass by reference?

Primitives are passed by value, and Objects are passed by "copy of a reference".

Specifically, when you pass an object (or array) you are (invisibly) passing a reference to that object, and it is possible to modify the contents of that object, but if you attempt to overwrite the reference it will not affect the copy of the reference held by the caller - i.e. the reference itself is passed by value:

function replace(ref) {
ref = {}; // this code does _not_ affect the object passed
}

function update(ref) {
ref.key = 'newvalue'; // this code _does_ affect the _contents_ of the object
}

var a = { key: 'value' };
replace(a); // a still has its original value - it's unmodfied
update(a); // the _contents_ of 'a' are changed

How to pass reference parameters as PHP in JavaScript?

Assign the return value to a variable.

const nextNumber = increase(number);
console.log(nextNumber);

where increase does the same thing as your PHP function:

function increase($value){ 
$value++;
return $value;
}

Passing variables between functions by reference in Google Apps Script

  • You want to call the value by the reference using Google Apps Script.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Issue and workaround:

Unfortunately, the variable of the number and string cannot be used as call by reference. For example, when the following script is run, 0.0, 0, 1.0, 1.0 can be seen at Logger.log.

function work(a, b, c, d) {
a = 1;
b = "1";
c[0] = 1;
d.value = 1;
}

function run() {
var a = 0;
var b = "0";
var c = [0];
var d = {value: 0};
work(a, b, c, d);
Logger.log("%s, %s, %s, %s", a, b, c[0], d.value) // 0.0, 0, 1.0, 1.0
}

So, in this case, please use the object like below.

Pattern 1:

In this pattern, an array is used as the object.

function MainFunc() {
var LoopCounter = [0];
SaveDataInArray(LoopCounter);
Logger.log(LoopCounter[0]);
}

function SaveDataInArray(LoopCounter) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var InfiniteForLoopTrigger = 1;
var range;
var VolumeArray = [];
var SignalArray = [];

//Save Data in Array
for(var i = 2; InfiniteForLoopTrigger > 0; i++){
range = s.getRange(i, 1);
if(range.isBlank()){
break;
}
VolumeArray[LoopCounter[0]] = s.getRange(i, 1).getValue();
SignalArray[LoopCounter[0]] = s.getRange(i, 2).getValue();
LoopCounter[0]++;
}
}

Pattern 2:

In this pattern, a JSON object is used as the object.

function MainFunc() {
var LoopCounter = {value: 0};
SaveDataInArray(LoopCounter);
Logger.log(LoopCounter.value);
}

function SaveDataInArray(LoopCounter) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var InfiniteForLoopTrigger = 1;
var range;
var VolumeArray = [];
var SignalArray = [];

//Save Data in Array
for(var i = 2; InfiniteForLoopTrigger > 0; i++){
range = s.getRange(i, 1);
if(range.isBlank()){
break;
}
VolumeArray[LoopCounter.value] = s.getRange(i, 1).getValue();
SignalArray[LoopCounter.value] = s.getRange(i, 2).getValue();
LoopCounter.value++;
}
}

If I misunderstood your question and this was not the direction you want, I apologize.

javascript pass object as reference

In JavaScript objects are always passed by copy-reference. I'm not sure if that's the exactly correct terminology, but a copy of the reference to the object will be passed in.

This means that any changes made to the object will be visible to you after the function is done executing.

Code:

var obj = {

a: "hello"

};

function modify(o) {

o.a += " world";

}

modify(obj);

console.log(obj.a); //prints "hello world"

Pass by reference vs Copy of reference

It has nothing to do with passing variable by reference or not.

In fact the problem is that you have put another object inside ref it doesn't point for the same object stored in user variable anymore.

function update(ref) {

//In this line we are reinitializing the value of ref with another object
ref = {
dep: "yyy"
};
ref.name = 'modified';
}

Demo :

Let's see the difference in this snippet:

var user = {

name: "xxx"

}

function update(ref) {

//Here we are updating ref/user

ref.before = "a value";



//And in this line we are reinitializing the value of ref with another object

ref = {

dep: "yyy"

};

ref.name = 'modified';

console.log('This is ref value: ');

console.log(ref);

}

update(user);

console.log('This is user value: ');

console.log(user);


Related Topics



Leave a reply



Submit