What is the string localeCompare() method in JavaScript?

The string.localeCompare() method is one of the built-in methods of the String class. This method compares the strings lexicographicallyComparison of a string or character in alphabetical order.

Syntax:

reference.localeCompare(compare)

Parameters

compare: The string that we compare lexicographically with reference.

Return value

The localeCompare() method returns the following values: 1, 0, -1.

Key guidelines:

  1. If string reference is lexicographically greater than string compare, the method returns 1.

  2. If string reference is lexicographically less than string compare, the method returns -1.

  3. If string reference is lexicographically equal to string compare, the method returns 0.

Code

Let’s look at the following coding example:

// alphabetically x comes before y.
a = 'x'.localeCompare('y');
// should be -1
console.log(a)
// alphabetically x comes after q.
b = 'x'.localeCompare('q');
// should be 1
console.log(b)
// comparing x with x
c = 'x'.localeCompare('x');
// should be 0
console.log(c)

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved