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

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

<!DOCTYPE html>
<html>
  <body>
    <pre id="output"></pre>
    <script>
      var str1 = 'hello world';
      var str2 = 'hello world';

      if (str1 == str2) {
        displayOutput = "The two strings are equal.";
      } else {
        displayOutput = "The two strings are not equal.";
      }
      document.getElementById('output').innerHTML = displayOutput;
    </script>
  </body>
</html>

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

index.html

<!DOCTYPE html>
<html>
  <body>
    <pre id="output"></pre>
    <script>
      var str1 = 'hello world';
      var str2 = 'apple';

      if (str1 == str2) {
        displayOutput = "The two strings are equal.";
      } else {
        displayOutput = "The two strings are not equal.";
      }
      document.getElementById('output').innerHTML = displayOutput;
    </script>
  </body>
</html>

Conclusion

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