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
I bet you didn't know that Javascript has pointers. Well, it does! Let's take a quick look at how they are implemented and how they work. We will also talk about possible reasons why pointers in Javascript are the way they are.
TL;DR: There are NO pointers in JavaScript and references work differently from what we would normally see in most other popular programming languages. 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.
Pointers are used extensively in both C and C++ for three main purposes: to allocate new objects on the heap, to pass functions to other functions. to iterate over elements in arrays or other data structures.
A pointer is a variable that stores the memory address of another variable as its value. A pointer variable points to a data type (like int ) of the same type, and is created with the * operator.
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.
This question may help: How to pass variable by reference in javascript? Read data from ActiveX function which returns more than one value
To summarise, Javascript primitive types are always passed by value, whereas the values inside objects are passed by reference (thanks to commenters for pointing out my oversight). So to get round this, you have to put your integer inside an object:
var myobj = {x:0}; function a(obj) { obj.x++; } a(myobj); alert(myobj.x); // returns 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With