14

This is an extremely basic question, I know, but I couldn't understand what's going on from Google and Stack Overflow.

I looked here and here to learn how to compare strings in JavaScript. Neither mentioned triple equals (===) in their answers, and said that it's better to use your own function (str1 < str2 ? -1 : str1 > str2).

However, going through explanations about === in Stack Overflow (here and here), the answers contain string comparisons. From what I saw in those answers, === does work for string comparisons, so why wasn't it included in the string comparison answers?

I'm just trying to expand my knowledge in JavaScript.

Thanks for any insight!

Community
  • 1
  • 1
Neta
  • 871
  • 5
  • 14
  • 30
  • 11
    Yes, `===` can compare two strings, giving `true` or `false` as a result. The other examples you saw were talking about comparing strings when *sorting* lists of them. – Pointy Nov 22 '15 at 18:12
  • You're correct. Thanks! – Neta Nov 22 '15 at 18:16
  • 1
    i dont think theres any advantage in using `===` instead of `==` when comparing thing you KNOW are going to be strings. `===` is usually for comparing things that will be multiple types. IE. `'0' !== 0`. I assume `==` is faster as well, but I'm much to lazy to find you benchmarks to back that up. – Rooster Nov 22 '15 at 18:19
  • 2
    You should only use === when the data type of the value matters, meaning when it could result in an undesirable behavior. Like if something requires a 0 to calculate but instead gets a false or a string '0' which can result in an inaccurate calculation or a string value that could choke a process. Triple-equals are so abused nowadays in JavaScript, I've had to fix multiple bugs in committed code to change the === to == when it wasn't necessary and caused problems (meaning it didn't matter what the data type was but checking the data type of '0' vs 0 caused the process to choke). – Davicus Apr 04 '18 at 00:23

2 Answers2

6
var str1 = "1";
var str2 = 1;
if (str1 == str2) {
      //Below code executes as it's true.
      console.log("Yes, value of both are equal.");
}

if (str1 === str2) {
     //Below code never executes as it's false.
     console.log("No, both are not equal as type differs.");
}

== compares value but === compares value as well as type. === can be used as string comparison but if you are sure that you are just comparing string then == should be sufficient. === is just a better choice.

Sudipta Kumar Maiti
  • 1,669
  • 1
  • 12
  • 18
  • 2
    Thanks for the example but I know what's the difference between `===` and `==`, that's not my question. – Neta Nov 22 '15 at 18:23
0

you can use both methods to compare strings, it just that you use === when you want to compare value AND type. what else is your query?

Shahsays
  • 421
  • 1
  • 7
  • 25