114

If I know x and y are both of type string, is the correct way to do string equality simply x == y?

The linter I'm using complains about this.

2

3 Answers 3

101

If you know x and y are both strings, using === is not strictly necessary, but is still good practice.

Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string rather than an actual string, which may complicate things.

Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===. Just go with that.

Sign up to request clarification or add additional context in comments.

Comments

6

Use below code for string comparison

if(x === y) {

} else {

}

Comments

-23

The === is not for checking string equalit , to do so you can use the Regxp functions for example

if (x.match(y) === null) {
// x and y are not equal 
}

there is also the test function

2 Comments

@Brain Well, I think that the opening statement is directly wrong. You can absolutely check for (string) equality with ===. And the tagged "possible duplicate answer" as well as this answer goes much into detail on comparisons. None of them suggests using .match()
This is wrong. === can (and should) be used to check for string equality, but match can't. For example, "^$".match("^$") returns null, "a".match(".") does not return null, and "(".match("(") is a runtime error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.