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:
In this JavaScript version:
We use zeroval to demonstrate pass-by-value for primitive types (like numbers).
We use zeroref with an object to demonstrate pass-by-reference behavior.
Instead of using pointers, we use object references to modify values indirectly.
We can’t print memory addresses in JavaScript, so we demonstrate object reference equality instead.
When you run this code, you’ll see:
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.