DEV Community

loading...

Discussion on: JS interview in 2 minutes / value vs reference

Collapse
nasrattalash profile image
Nasratullah Talash

I think the thing that @Lukáš Zahradník is doing, is making the x variable refer to a new object. That is the reason the object passed from outside into function in his example is not getting modified.
There is a difference between using a reference to add new properties/bringing changes to the reference type variable and referring to a completely new object.

let x = {a: 0};
function changeRefType(refType) {
  refType.b = 2; // add b property to object referred by refType variable
}
changeRefType(x);
console.log(x); // output: {a: 0, b: 2}

// Make variable refer to new object
function assignNewObj(refType) {
  refType = {name: "Bob"}; // refType (functions local variable) made to refer to new object
  console.log(refType); // output: {name: "Bob"}
}
assignNewObj(x);
console.log(x); // x is still refers to object created in first line, modified in changeRefType function
// output: {a: 0, b: 2}
Enter fullscreen mode Exit fullscreen mode
Collapse
lukaszahradnik profile image
Lukáš Zahradník

You are correct. But the behavior I described is what the passing by reference is about (which isn't possible in JS). Check out for example passing by reference in C# (docs.microsoft.com/en-us/dotnet/cs...) via ref keyword.