DEV Community

Discussion on: Troll Hunting 101: JavaScript Passes Objects by Reference

Collapse
 
devdufutur profile image
Rudy Nappée • Edited

Hi @bytebodger , I always like reading your posts, and the iconoclastic way you're doing it ;)

But here, I have to disagree (sorry !) when you say :
"You know what's another name for "pointer"??? Reference"

Pointers and references doesn't work the same way. When you reassign a pointer locally, the caller keep the former pointer. With a reference, if you reassign the variable, the caller gets the new value.

Take the following in C++ (a language which allow explicit pointers & allow you passing parameters by reference or by value) :

// Example program
#include <iostream>
#include <string>

class SomeStuff {
    public:
        int someInt;
        SomeStuff(int anInt) {
            someInt = anInt;
        }
};

void reassignReference(SomeStuff & someStuff) {
    someStuff = SomeStuff(42); // the referenced value has been changed
}

void reassignPointer(SomeStuff * someStuff) {
    someStuff = new SomeStuff(42); // the pointer is reassigned locally
}


int main()
{
  std::cout << "This is call by reference !" << std::endl;
  SomeStuff three(3);
  std::cout << "before reassignReference() : " << three.someInt << std::endl;
  reassignReference(three);
  std::cout << "after reassignReference() : " << three.someInt << std::endl;

  std::cout << "This is call by value !" << std::endl;
  SomeStuff * four = new SomeStuff(4);
  std::cout << "before reassignPointer() : " << four->someInt << std::endl;
  reassignPointer(four);
  std::cout << "before reassignPointer() : " << four->someInt << std::endl; // the pointed object hasn't changed
}
Enter fullscreen mode Exit fullscreen mode
This is call by reference !
before reassignReference() : 3
after reassignReference() : 42
This is call by value !
before reassignPointer() : 4
before reassignPointer() : 4
Enter fullscreen mode Exit fullscreen mode

Do we agree that if JS behave the same way than first portion, it means JS uses call-by-reference, if not it uses call-by-value ?

Let's try :

function reassign(someStuff) {
    someStuff = { someInt: 42 };
}

console.log("This is call by -what- ?");
let three = { someInt: 3 };
console.log("before reassign", three);
reassign(three);
console.log("after reassign", three);
Enter fullscreen mode Exit fullscreen mode

output :

This is call by -what- ?
before reassign {someInt: 3}
after reassign {someInt: 3}
Enter fullscreen mode Exit fullscreen mode

It seems parameters are passed by value in JS.

Are we agree now ? :)