This post will discuss how to pass a variable by reference in JavaScript.

There is no built-in way to pass a variable by reference in JavaScript, as JavaScript always passes arguments by value, not by reference. However, there are some possible workarounds to achieve a similar effect, depending on our use case and preference. Here are some of the common functions:

1. Using an object property

We can wrap the variable in an object and pass the object as an argument to a function. Then, we can modify the object property inside the function, and the change will be reflected outside the function as well. This is because objects are passed by value of their reference, meaning that the function receives a copy of the reference to the same object in memory. Here’s an example of how we can achieve this:

Download  Run Code

2. Using a closure

We can create a function that returns another function that has access to a local variable in its outer scope. This way, we can create a private variable that can only be modified by the inner function, and return the inner function as a reference to the variable. Here’s an example of how we can achieve this:

Download  Run Code

3. Using a generator

A third way is to use a generator, which is a special kind of function that can yield multiple values and resume its execution. We can create a generator that takes an integer as an argument and yields incremented values when called. Here’s an example of how we can achieve this:

Download  Run Code

4. Using an array

Finally, we can put the variable in an array and pass the array as an argument. Then, we can modify the array element inside the function and it will affect the original array. For example:

Download  Run Code

That’s all about passing a variable by reference in JavaScript.