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
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:
-
If string
referenceis lexicographically greater than stringcompare, the method returns1. -
If string
referenceis lexicographically less than stringcompare, the method returns-1. -
If string
referenceis lexicographically equal to stringcompare, the method returns0.
Code
Let’s look at the following coding example:
// alphabetically x comes before y.a = 'x'.localeCompare('y');// should be -1console.log(a)// alphabetically x comes after q.b = 'x'.localeCompare('q');// should be 1console.log(b)// comparing x with xc = 'x'.localeCompare('x');// should be 0console.log(c)
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved