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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Since JavaScript does not support passing parameters by reference, you’ll need to make the variable an object instead:
In this case,
xis a reference to an object. Whenxis passed to the functiona, that reference is copied over toobj. Thus,objandxrefer to the same thing in memory. Changing theValueproperty ofobjaffects theValueproperty ofx.Javascript will always pass function parameters by value. That’s simply a specification of the language. You could create
xin a scope local to both functions, and not pass the variable at all.