Sometimes, we want to pass a reference of a variable that is immutable as argument in a function with JavaScript.
In this article, we’ll look at how to pass a reference of a variable that is immutable as argument in a function with JavaScript.
How to pass a reference of a variable that is immutable as argument in a function with JavaScript?
To pass a reference of a variable that is immutable as argument in a function with JavaScript, we can make the function accept an object.
For instance, we write
const x = { value: 0 };
const a = (obj) => {
obj.value++;
};
a(x);
console.log(x.value);
to define the x
object and a
function.
In a
, we increment the value
property by 1.
Then we call a
with x
.
As a result, x.value
is 1 since objects are passed by reference.
Conclusion
To pass a reference of a variable that is immutable as argument in a function with JavaScript, we can make the function accept an object.