Categories
JavaScript Answers

How to pass a reference of a variable that is immutable as argument in a function with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *