DEV Community

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

Collapse
 
bytebodger profile image
Adam Nathaniel Davis • Edited

This confuses beginners to no end, so I find it interesting that this debate also exists in the JavaScript world!

I didn't even realize that there was much of a "debate" about this - until I started reading Dev.to articles and noticed the disturbing number of people who feel compelled to jump in every single time they see any writer commit the sin of implying that JS has pass-by-reference.

BTW, I think this argument (which you present as being used by trolls) is valid and doesn't change the fact that in practice, objects are passed by reference:

Agreed. And to be clear, I'm not saying that everyone who discusses the inner workings of JS pass-by-value/reference is a troll. But I've seen numerous cases, where someone references JS pass-by-reference, and one-or-two users feel compelled to litter the comments with a bunch of base refusals that "pass-by-reference" even exists in JS.

I think seeing it that way actually helps understand how it works: the variable's value isn't the object itself, it's a reference to the object.

Totally agree.

(Yes, I realize this could be seen as pedantry, but I think it gives an interesting perspective on how things actually work under the hood).

I don't think you're being pedantic at all. And there's nothing wrong with diving deeply into a language's gears to understand how it's really working. Here's where I've seen this turn into pedantry:

A dev copies an object into a new variable, alters some of the keys/values inside the new variable, and is then surprised to find the original object has been altered. When someone explains that this is because objects are passed by reference, some Snark Lord jumps in to "correct" them because, "JS always passes by value".

In most scenarios, if I say that this variable holds a reference, and someone tries to correct me by saying that the variable holds "a value - which holds a reference" - that someone is probably being a jerk. Even worse, they're probably making the subject much more confusing to anyone else who doesn't have a firm grasp of the underlying mechanics.

Imagine if you tell me that your couch is in your living room. And I decide that I should "correct" you by stating that there's an area in your living room, which contains the couch.

It's basically like having that guy in the room who feels compelled to constantly correct minor details in everyone else's conversation by butting in with, "Actually..."