How to Pass the Value (Not the Reference) of a Js Variable to a Function

How do I pass the value (not the reference) of a JS variable to a function?

In modern browsers, you can use the let or const keywords to create a block-scoped variable:

for (let i = 0; i < results.length; i++) {
let marker = results[i];
google.maps.event.addListener(marker, 'click', () => change_selection(i));
}

In older browsers, you need to create a separate scope that saves the variable in its current state by passing it as a function parameter:

for (var i = 0; i < results.length; i++) {
(function (i) {
marker = results[i];
google.maps.event.addListener(marker, 'click', function() {
change_selection(i);
});
})(i);
}

By creating an anonymous function and calling it with the variable as the first argument, you're passing-by-value to the function and creating a closure.

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

How to pass the value of a variable instead of a reference into a function in Javascript

Use an IIFE that captures the current value of a.

var a = 5;
document.getElementById("element").onclick = ((x) => ()=>alert(x))(a);
a = 10;
<button id="element">Click</button>

How to make sure the variable is not passed by reference

You can copy an Array with many methods, give a look to this jsperf to see which method is faster.

var myArray = [1,2,3];
var myClone = clone( myArray );

function clone ( toClone ) {
a = [];

for ( i = toClone.length; i--; ) {
a.push( toClone[i] );
}

return a;
}

it seems that the iteration is the fastest, but be aware of that if the elements in your array are Objects the will not be copied, but referenced.

var myArray = [{},{},{}];
var myClone = clone( myArray );
myClone[0].foo = 'bar';
console.log( myArray[0].foo ); // 'bar'

Passing a pointer/reference to a variable as parameter

What you've described wanting to do doesn't immediately say "use a reference to a variable" to me (as Teemu points out, sounds like you want debouncing), but answering your question about references to variables...

JavaScript doesn't have any form of references to variables (other than through closures, which might be problematic here). But you can readily do what you're talking about by just using an object and using a property on it. The property is the "variable."

Simple example:

function foo(obj) {  var counter = 0;  var timer = setInterval(function() {    console.log("foo: " + obj.property);    if (++counter === 5) {      clearInterval(timer);    }  }, 500);}
var o = {property: "unchanged"};// Give the "reference" to `property` to `foo`:foo(o);
// Update it periodically while `foo` is doing its asynchronous thingsetTimeout(function() { o.property = "update 1";}, 1000);setTimeout(function() { o.property = "update 2";}, 1700);

Passing a reference of a global variable to a function

Primitive values aren't passed by reference.
Objects are.

If you wrap the globals in an object, you'll be able to modify its properties from a function:

var data_1 = {};var data_2 = {};

fillValue(data_1,"First");fillValue(data_2,"Second");
function fillValue(link2GlobalVar, value){ link2GlobalVar.value = value;}
document.write(data_1.value + "<br/>" +data_2.value);


Related Topics



Leave a reply



Submit