Since arrays are essentially objects in javascript, each array here is a pointer to a location in memory; hence, both == and === will give false. Similarly, < and > will also give false. However, <= and >= gives true when two arrays with the same items in the same order are compared. I would appreciate it if someone could explain what's going on under the hood here.
Asked
Active
Viewed 63 times
2
-
3it's comparing them as strings. also, this has nothing to do with pointers or memory locations, that's all abstracted "under the hood". – dandavis Oct 23 '19 at 18:35
-
Generally, string type-casting kicks in when one of the compared items is a string as it is with '==' for example. Any idea why the arrays are being type-casted to string since both the compared items are essentially arrays here? – Rohan Dhar Oct 23 '19 at 18:38
-
2Arrays cannot be directly compared with less-than or greater-than operators, so they are converted to something that can. The `<` and `>` operators call `valueOf` on each value being compared before performing the comparison. You can read about that [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf) – Oct 23 '19 at 18:39
-
2the exact order of coerced comparison attempts varies by a lot of factors, it's complicated. check the spec. it's actually not that complicated if you keep a few simple rules in mind, but they are not always the most obvious to non-js devs. there is a way to make your objects compare in a custom fashion, if that interests you. – dandavis Oct 23 '19 at 18:40
-
1@RohanDhar it's how [relational comparison works](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Relational_operators). It makes no sense to compare which object is "less than" another object, so when relational comparison is employed, both operands are converted to primitives through `valueOf` – VLAZ Oct 23 '19 at 18:41
-
2JavaScript has all sorts of unintuitive rules for how types get converted when you try to perform operations on them that they can't do natively. I find it's best to avoid it all and just use the correct type for what you're trying to do in the first place. – John Montgomery Oct 23 '19 at 18:41