DEV Community

loading...
Cover image for JS interview in 2 minutes / value vs reference

JS interview in 2 minutes / value vs reference

Nikita Kozlov
Make things happen ✨ Webdev / websec / management / drawing
・1 min read

Question:
Explain passed by value and passed by reference.

Quick answer:
In JavaScript, all primitive values are passed by value, but all non-primitive types are passed by reference. This means you can change params and this change will be isolated (with no side-effects).

Longer answer:
So the primitive types in JavaScript are undefined, Boolean, String, and others.

Structural types (non-primitive) are Object and Function. Needed to mention that arrays and other structures have an Object type too.

This means when you pass some value to the function its behavior will depend on its type.

carbon (4)

Real-life example:
In real-life apps, you need to be extra careful when changing any of provided function params, because debugging issues like this can be super tricky and time-consuming.

carbon (5)

This is how you can fix this issue:

carbon (3)

UPD: As @lukaszahradnik mentioned in comments, it is actually based by sharing, but not by reference. Thanks for clearing this up! 🙏


Other things to read:

Also, I will post more fun stuff here and on Twitter let's be friends 👋

Discussion (12)

Collapse
smac89 profile image
smac89 • Edited

I don't think pass-by-reference exists in JavaScript. That's a term popularized by C++ or C. In those languages, objects can either be values or reference, therefore you need the pass-by-semantics to differentiate between the two.

JavaScript is more similar to Java in that both languages have no concept of value types. All objects are references, which means all values are references too, therefore there is no need to make a distinction about call semantics. (Actually now Java has Record types which are kinda like value types, except that they are only shallowly immutable). Therefore, every time you pass an object to a function, if that object is mutable, any changes made to it will reflect outside the function.

i.e. if the Boolean type had a mutable field, you will see that mutation after passing that boolean to a function which changes it. The same will not be true in languages with true value types like C++ or C. A value type in C++, even with mutable fields will not reflect in the original object outside the function, if the function were to mutate it.

Collapse
kozlovzxc profile image
Nikita Kozlov Author

Hey 👋 Not sure if I'm following if this comment describing the same issue as this one or is it another issue? Can you take a look at the previous one?

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.

Collapse
lukaszahradnik profile image
Lukáš Zahradník

There is no "passed by reference" in JavaScript.

Collapse
javier123454321 profile image
Javier Gonzalez

I dont follow, have a link or care to elaborate? You can pass an object as a parameter and change its internals inside the scope of a function. I understand this as pass by reference, am I mistaken?

Collapse
lukaszahradnik profile image
Lukáš Zahradník • Edited

What you described is "call by sharing" (en.wikipedia.org/wiki/Evaluation_s...).

Passing by reference would mean that it is possible to modify the passed variable, such as

function modifyVariable(x) {
    x = {b: 0};
}

let a = {a: 0};
modifyVariable(a);
Enter fullscreen mode Exit fullscreen mode

variable a now should be equal to {b: 0} if it was passed by reference.

Thread Thread
javier123454321 profile image
Javier Gonzalez

I see it's not a direct reference to the variable because you cant reasign that reference, however, you do have access to the internals of the parameter that was passed. Thanks for clearing that up, I have often heard that you pass by reference in javascript but TIL.

Thread Thread
kozlovzxc profile image
Nikita Kozlov Author

Thanks for the detailed answer @lukaszahradnik and thanks for asking for more details @javier123454321 🙏 I have added update notes to the post itself.

Thanks again for clarifying this!

Collapse
perpetual_education profile image
perpetual . education

This is still one of the hardest things to explain to our students. This conversation is great.

Collapse
kozlovzxc profile image
Nikita Kozlov Author

Thanks ✨

Collapse
goddard profile image
Ryein Goddard • Edited

Haha js devs trying to be c++ devs now.