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

You can also use the == operator, which checks only the value and performs type coercion if necessary. However, it’s generally recommended to use === for strict equality checks to avoid unexpected behavior.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading