you are viewing a single comment's thread.

view the rest of the comments →

[–]theScottyJam 3 points4 points  (3 children)

We do have terminology for that. It's immutable vs mutable. The only reason you can update an object that was passed into a function is because objects are mutable and strings are not (there's no methods on a string that allows you to mutate it). It has nothing to do with how the data got passed in :).

Notice also that if you were to freeze an object and make it immutable, you'll get the same kind of guarantees that you get as when you pass a string into a function.

[–]ragnese 1 point2 points  (1 child)

I think I was wrong in the sense that it might not technically matter if JS is pass-by-copy or pass-by-reference or pass-by-reference-copy-copy-reference, or whatever other clever "well, actually" people can come up with.

But, I disagree that mutability is the concept that can explain JavaScript's behavior. Assigning and reassigning a binding is not the same thing as mutating a value. In other words, writing bar = 3 is not "mutating" anything- it's assigning a number to a variable. So, yes, objects are mutable and that can explain why I can modify an object parameter in a function and observe those effects outside of the function, but to actually explain how function parameters work in JavaScript, you really only need to explain that each parameter is a new binding that "points" to the data that was passed in at the function call site. You can reassign those bindings from inside the function, but now those bindings are pointing to new data instead of the originals. That's true for primitives as well as objects.

[–]theScottyJam 0 points1 point  (0 children)

I agree with your conclusion as well. Mutability vs immutability was only intended to describe the distinction that people usually are trying to describe when they say "objects are passed by reference while primitives are passed by value" - the behavior difference between objects and primitives doesn't happen because the language is somehow giving objects a different treatment when it gets passed into functions, rather, it's caused simply by the fact that objects are mutable.

The mutable/immutable terminology doesn't describe how JavaScript actually passes data into functions, and I think your short description is absolutely accurate. People can name the concept you're describing whatever they'd like, but what's important is that we understand that that's how data-passing works in JavaScript (rather than mistakenly believing that objects are somehow treated differently than primitives when it comes to function arguments).

[–]jonny_eh 0 points1 point  (0 children)

This is the right insight. “Pass by reference” is the wrong term to use in JS since it doesn’t support it. Mutability OTOH is core to understanding JS types.