JavaScript – Check if Two Strings are Equal

To check if two strings are equal in JavaScript, use equal-to operator == and pass the two strings as operands. The equal-to operator returns a boolean value of true if the two strings are equal, or else, it returns false.

Equal-to operator considers the case while comparing the strings. a and A are not equal.

Syntax

The boolean expression (or condition) to check if strings: str1 and str2 are equal, using equal-to operator is

str1 == str2
ADVERTISEMENT

Examples

The following is a quick example to check if two strings are equal in JavaScript.

var str1 = 'hello world';
var str2 = 'hello world';
if (str1 == str2) {
    //strings are equal.
} else {
    //strings are not equal.
}

In the following example, we take two strings in script, and check if these two strings are equal.

index.html

Now, let us take values in the strings, such that the strings are not equal, and observe the output.

index.html

Conclusion

In this JavaScript Tutorial, we learned how to check if two strings are equal in JavaScript, using equal-to operator, with examples.