0
0
JavascriptHow-ToBeginner · 3 min read

How to Compare Strings in JavaScript: Syntax and Examples

In JavaScript, you compare strings using the === operator for exact equality or localeCompare() method for alphabetical order. Use === to check if two strings are exactly the same, and localeCompare() to find their relative order.
📐

Syntax

To compare strings for equality, use the === operator which checks if both strings have the same characters and length.

To compare strings alphabetically, use the string1.localeCompare(string2) method which returns a number indicating their order.

javascript
const string1 = "apple";
const string2 = "banana";

// Equality check
const areEqual = string1 === string2;

// Alphabetical order check
const order = string1.localeCompare(string2);
💻

Example

This example shows how to check if two strings are equal and how to compare their alphabetical order using localeCompare().

javascript
const str1 = "hello";
const str2 = "hello";
const str3 = "world";

console.log(str1 === str2); // true
console.log(str1 === str3); // false

console.log(str1.localeCompare(str3)); // negative number (str1 comes before str3)
console.log(str3.localeCompare(str1)); // positive number (str3 comes after str1)
console.log(str1.localeCompare(str2)); // 0 (strings are equal)
Output
true false -1 1 0
⚠️

Common Pitfalls

One common mistake is using == instead of ===, which can cause unexpected type coercion. Always use === for string comparison.

Another pitfall is comparing strings with different letter cases. For case-insensitive comparison, convert both strings to the same case using toLowerCase() or toUpperCase() before comparing.

javascript
const a = "Hello";
const b = "hello";

// Wrong: case-sensitive comparison
console.log(a === b); // false

// Right: case-insensitive comparison
console.log(a.toLowerCase() === b.toLowerCase()); // true
Output
false true
📊

Quick Reference

MethodDescriptionReturns
=== operatorChecks if two strings are exactly equaltrue or false
localeCompare()Compares strings alphabeticallyNegative, 0, or Positive number
toLowerCase() / toUpperCase()Converts strings to same case for case-insensitive comparisonNew string in lower or upper case

Key Takeaways

Use === to check if two strings are exactly the same.
Use localeCompare() to compare strings alphabetically.
Convert strings to the same case for case-insensitive comparison.
Avoid == operator to prevent unexpected type coercion.
localeCompare() returns a negative, zero, or positive number indicating order.