Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
15
rated 0 times [  18] [ 3]  / answers: 1 / hits: 136396  / 12 Years ago, thu, april 19, 2012, 12:00:00

Can we pass a reference of a variable that is immutable as argument in a function?



Example:



var x = 0;
function a(x)
{
x++;
}
a(x);
alert(x); //Here I want to have 1 instead of 0

More From » javascript

 Answers
5

Since JavaScript does not support passing parameters by reference, you'll need to make the variable an object instead:



var x = {Value: 0};

function a(obj)
{
obj.Value++;
}

a(x);
document.write(x.Value); //Here i want to have 1 instead of 0





In this case, x is a reference to an object. When x is passed to the function a, that reference is copied over to obj. Thus, obj and x refer to the same thing in memory. Changing the Value property of obj affects the Value property of x.



Javascript will always pass function parameters by value. That's simply a specification of the language. You could create x in a scope local to both functions, and not pass the variable at all.


[#86131] Wednesday, April 18, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaquelineh

Total Points: 360
Total Questions: 105
Total Answers: 114

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;