Add equals() method to the String class?

I'm fairly new to web dev and my expertise is in C/C++, Java, and Python. I am perplexed by the complexity of comparing two strings in JavaScript. Look no further than stackoverflow. Because I come from a C/C++/Java background, I oftentimes wonder why JavaScript doesn't have a ".equal()" method like Java and other languages.

In my opinion, it seems like a no-brainer decision considering that one of JavaScript's founding principles was to have a degree of familiarity with other programming languages. Furthermore, adding one of the above methods will temporarily solve the "===" and "==" confusion that is rampant in the JavaScript community. It has potential to save programmers from costly bugs that can result from the confusion between "==" and "===".


var drink = "coffee";
if (drink.equals("coffee")) {

Because it doesn't need one :-) Python has none either, btw - for slightly different reasons though.

I disagree. On the contrary, it will add to the confusion, now having three choices instead of two. "How is a.equals(b) different from a === b?", everyone will ask. Different Unicode handling perhaps?

I thought that problem was long solved, by simply recommending to always use ===. (At least until the difference is understood and one knows when == is safe).


strings follow value equality rules in js, so we can use the triple equal to compare it. java has that because strings are objects in java, iirc.

double equal is due to some historic reasons, that we don't really think about anymore. Linters, IDEs, Typescript will remind you not to use that.

Your linked stackoverflow question, unfortunately, has, as the top answer, an answer which adds to the confusion between == and ===. As mentioned, the standard practice is to just always use === and to never use ==, some people choosing to allow, as the only exception, x == null (which is a convenient shorthand for x === undefined && x === null. That's it. So, if you want to do a string comparison, it's as simple as str1 === str2.

=== is supposed to be the better version of ==, and there isn't supposed to be a need to use == anymore. But, as with every standard practice in JavaScript you'll always find a subset of the community who questions what the crowd is following and finds arguments for doing things a different way. This isn't a bad thing, it's always good to be inquisitive, but it does add to the confusion when a newcomer is looking for the "standard" way of doing something and they see, as the top-voted answer, an answer that encourages experienced developers to experiment with alternative approaches.

1 Like

I often use == to test for numeric strings;
It is useful for union types such as

let value: number | string;
let nullish: null | undefined;

Especially useful when dealing with css in js;
Apart from neiche uses like that, I guess it's better to use ===