DEV Community

loading...

Discussion on: A "Gotcha" of JavaScript's Pass-by-Reference

Collapse
functional_js profile image
Functional Javascript • Edited

Here's an example from the C# docs (though massively naive and antipattern-ish, because one would never have to do this). Notice two ref keywords must be used, in the caller and callee.
Btw, I've coded in C# for years and I've never used it, and never seen it used. It really shouldn't exist.

class PassingRefByRef
{
    static void Change(ref int[] pArray)
    {
        // Both of the following changes will affect the original variables:
        pArray[0] = 888;
        pArray = new int[5] {-3, -1, -2, -3, -4};
        System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]);
    }

    static void Main()
    {
        int[] arr = {1, 4, 5};
        System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr[0]);

        Change(ref arr);
        System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr[0]);
    }
}
/* Output:
    Inside Main, before calling the method, the first element is: 1
    Inside the method, the first element is: -3
    Inside Main, after calling the method, the first element is: -3
*/

Enter fullscreen mode Exit fullscreen mode
Thread Thread
netional profile image
Netional

I recently came across a Typescript use case (admittedly seldom happens) for reference to the reference in which I wanted to have a function that disposes of passed in class members and set them to undefined. This is not possible in JS or Typescript as far as I can see.

private DisposeOrbitalControls(orbitControls: OrbitControls | undefined): void {
    if (orbitControls !== undefined) {
      orbitControls.dispose();
      orbitControls = undefined
    }
}

this.DisposeOrbitalControls(this.orbitControlsOrtho)
this.DisposeOrbitalControls(this.orbitControlsPerspective)
//this.orbitControlsOrtho and this.orbitControlsPerspective are not set to undefined
Enter fullscreen mode Exit fullscreen mode

Some comments have been hidden by the post's author - find out more