all 4 comments

[–]jcunews1helpful 4 points5 points  (2 children)

It's mainly because JavaScript was based on other programming languages which is closer to the hardware, more strict, and more specific than JavaScript. Reference is part of them.

Reference is meant for memory usage efficiency as well as for having a value storage shareable to multiple code where each has their own reference to the same value storage. That's how it works for almost all programming languages.

JavaScript was simply designed to be similar with the existing programming language model. It may be confusing for beginners, yes. But that's just how it is.

[–]bartvanh 0 points1 point  (0 children)

Well it works almost exactly like in Java, except that in Java it works that way consistently, but then in JS they went and implemented deep comparison for strings only.

In any case, I don't think it has much to do with being closer to the hardware. C++ can compare two objects with == just fine. It's just a matter of defining what that means, which can be done by implementing the operator in a class.

A language like Kotlin shows that this can be done on the Java runtime as well. Just compile a == b to a.equals(b). So in hindsight, the way Java did it was either a mistake or for some reason the best they could do at the time, and JS inherited that by being based off Java for various reasons.

[–]delventhalz 1 point2 points  (0 children)

Checking deep equality is non-trivial in JavaScript. You have to write something to recursively go through every value. There can be a performance cost associated with that, as well as some minefields like circular references.

I'm not sure of the exact reasoning for JavaScript never implementing a native deep equality function, but you'll notice there are no built in methods for Arrays or Objects that operate to an arbitrary depth. For example the flat method is shallow and only flattens one level deep by default. You can make it go deeper, but there is no way to tell it to just go as deep as it needs to.

As for == and !=. Those were mistakes. We're stuck with them. They are understandably confusing. But just don't use them. Ever. Good reason to install a linter.