DEV Community

Discussion on: JavaScript, Ruby and C are not call by reference

Collapse
 
peerreynders profile image
peerreynders • Edited

A reference is simply a memory address that is automatically dereferenced by the language/runtime.

From that point of view

// (01) primitiveValue stores address #A
var primitiveValue = 1;
// (02) someObject stores address #B
var someObject = { is: 'changed?' };

// (03) myRefMaybe stores address #A from primitiveValue
reference_assignment(primitiveValue);
// (06) primitiveValue still has address #A
primitiveValue;

// (07) myRefMaybe stores address #B from someObject
reference_assignment(someObject);
// (10) someObject still has address #B
someObject;

function reference_assignment(myRefMaybe) {
  // (04) myRefMaybe still has address #A
  // (08) myRefMaybe still has address #B
  myRefMaybe = { key: 42 };
  // (05) myRefMaybe now has address #C
  // (09) myRefMaybe now has address #D
}
Enter fullscreen mode Exit fullscreen mode

if myRefMaybe was a reference, then re-assigning the value of that reference, would change the original definition too

To be able to change the "original definition" you would need the reference to the someObject reference itself (rather than the reference to the original object):

  • if someObject stores the address #B to the actual object
  • and that address #B is stored on behalf of someObject at address #Z
  • you need to place address #C at address #Z so that someObject now stores the address #C to that other object.

Update:

  • Call by Value: Copy the actual value.
  • Call by Sharing: Copy the address to the value.This makes it possible to share the value but not possible to replace the original value at the source variable.
  • Call by Reference: Copy the address of the "variable". This makes it possible to replace the original value at the source variable.

The way JavaScript behaves it actually never has to store anything at the address that is found in a variable - it only stores new addresses in variables.

  // (1) `myRefMaybe` has address #B as set by caller
  myRefMaybe = { key: 42 };
  // (2) New value `{ key: 42 }` is created
  // (3) `myRefMaybe` stores address #C to new value
Enter fullscreen mode Exit fullscreen mode