Skip to content

JavaScript equals string | Example code

  • by

Use strict equality operator === to check for JavaScript equals string. This has the advantages of being the most efficient and reducing the chances of buggy or uncertain code.

Source: MDN Web Docs: Strict Equality.

If you know they are strings, then there’s no need to check for type.

"a" == "b"

However, note that string objects will not be equal.

new String("a") == new String("a") //false

Call the valueOf() method to convert it to a primitive for String objects,

new String("a").valueOf() == new String("a").valueOf()//true

String equals in JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
   var a = "hello1";
   var b = "hello1";
   var c = "hello2";

   console.log("a === a?", (a === a));
   console.log("a === b?", (a === b));
   console.log("a === c?", (a === c));

 </script>

</body>
</html>

Output:

JavaScript equals string

Alphabetical Comparisons

If you want to compare two strings to know if a string comes before or after another string, based on natural sorting, use the <, >, <=, and >= operators. Source: MDN WebDocs for <, >, <=, and >=.

    var a = "hello1";
    var b = "hello2";
    console.log("a < a?" + (a < a));
    console.log("a < b?" + (a < b));
    console.log("a > b?" + (a > b));
    console.log("b > a?" + (b > a));

Output:

a < a?false
a < b?true
a > b?false
b > a?true

Do comment if you have any doubts or suggestions on this Js string topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *