Pointers in JavaScript

JavaScript doesn’t have explicit pointer types like some other languages. However, we can demonstrate similar concepts using object references and value/reference passing. Here’s an equivalent example:

// We'll show how references work in contrast to values with
// 2 functions: `zeroval` and `zeroref`. `zeroval` takes a
// number parameter, so arguments will be passed to it by
// value. `zeroval` will get a copy of `ival` distinct
// from the one in the calling function.
function zeroval(ival) {
    ival = 0;
}

// `zeroref` in contrast takes an object parameter. In JavaScript,
// objects are passed by reference. Modifying the object inside
// the function will affect the original object.
function zeroref(iobj) {
    iobj.val = 0;
}

function main() {
    let i = 1;
    console.log("initial:", i);

    zeroval(i);
    console.log("zeroval:", i);

    // We create an object to demonstrate reference passing
    let obj = { val: i };
    zeroref(obj);
    console.log("zeroref:", obj.val);

    // In JavaScript, we can't print memory addresses,
    // but we can show that two variables reference the same object
    let obj2 = obj;
    console.log("same reference:", obj2 === obj);
}

main();

In this JavaScript version:

  1. We use zeroval to demonstrate pass-by-value for primitive types (like numbers).
  2. We use zeroref with an object to demonstrate pass-by-reference behavior.
  3. Instead of using pointers, we use object references to modify values indirectly.
  4. We can’t print memory addresses in JavaScript, so we demonstrate object reference equality instead.

When you run this code, you’ll see:

initial: 1
zeroval: 1
zeroref: 0
same reference: true

zeroval doesn’t change the i in main, but zeroref does because it has a reference to the object containing the value. This mimics the behavior of the original example, where zeroptr modified the value through a pointer.

In JavaScript, all objects are passed by reference, which is similar to passing a pointer in other languages. Primitive values (like numbers, strings, booleans) are passed by value.