JavaScript String localeCompare() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Instance method

What You’ll Learn

String.prototype.localeCompare() returns a number that tells you how two strings order in a given language (same API as MDN String.prototype.localeCompare()). Learn negative / positive / 0 results, locales and options, sensitivity, numeric sorting, when to prefer Intl.Collator, five examples, and try-it labs.

01

Kind

Instance method

02

Returns

number (<0 / 0 / >0)

03

Locales

Optional

04

Options

sensitivity, numeric…

05

Mutates?

No

06

Baseline

Widely available

Introduction

Sorting names, product titles, or filenames often needs language rules — not raw character codes. In German, "ä" may sort near "a"; in Swedish it can sort after "z". That is what localeCompare() is for.

It returns a number you can use in Array.prototype.sort: negative means “this string comes first,” positive means “comes later,” and 0 means “same for this comparison.” Engines with Intl.Collator support delegate to that API.

💡
Beginner tip

Do not check for exactly -1 or 1. Use < 0, > 0, or Math.sign() — engines may return other negative or positive integers.

This page is part of JavaScript String Methods. Related topics include includes() and indexOf().

Understanding the localeCompare() Method

Call referenceStr.localeCompare(compareString) to ask: “Where does referenceStr sit relative to compareString in sort order?”

  • NegativereferenceStr comes before compareString.
  • PositivereferenceStr comes after compareString.
  • Zero — they are equivalent for the chosen locale / options.
  • Optional locales and options customize language rules (same idea as Intl.Collator).

📝 Syntax

General forms of String.prototype.localeCompare:

JavaScript
str.localeCompare(compareString)
str.localeCompare(compareString, locales)
str.localeCompare(compareString, locales, options)

Parameters

  • compareString — the string to compare against. Coerced to a string (undefined becomes "undefined").
  • locales (optional) — a BCP 47 language tag (e.g. "fr", "de", "sv") or an array of tags. Ignored on rare engines without Intl.Collator.
  • options (optional) — an options object (same shape as Intl.Collator), e.g. { sensitivity: "base" }, { numeric: true }, { ignorePunctuation: true }.

Return value

A number. Special cases:

SituationReturns
str sorts before compareStringA negative number (e.g. -1 or -2)
str sorts after compareStringA positive number (e.g. 1 or 2)
Equivalent under the rules0
With Intl.CollatorSame as new Intl.Collator(locales, options).compare(str, compareString)

Common patterns

JavaScript
Math.sign("a".localeCompare("c"));      // -1  (before)
Math.sign("check".localeCompare("against")); // 1 (after)
"a".localeCompare("a");                 // 0

// Sort an array (French + ignore punctuation):
const items = ["réservé", "Premier", "café", "Adieu"];
items.sort((a, b) => a.localeCompare(b, "fr", { ignorePunctuation: true }));

// Many comparisons → reuse a collator:
const collator = new Intl.Collator("en", { sensitivity: "base" });
items.sort(collator.compare);

⚡ Quick Reference

GoalCode
Compare two stringsa.localeCompare(b)
Stable signMath.sign(a.localeCompare(b))
Sort arrayarr.sort((a, b) => a.localeCompare(b))
Language-specifica.localeCompare(b, "de")
Ignore case / accents{ sensitivity: "base" }
Numeric "2" before "10"{ numeric: true }
Many sortsnew Intl.Collator(...).compare

🔍 At a Glance

Four facts to remember about String.localeCompare().

Returns
number

<0 / 0 / >0

Exact -1?
no

Use sign only

Best for
sort()

Locale-aware order

Mutates
no

Strings stay immutable

📋 localeCompare() vs < / > vs Intl.Collator

localeCompare()a < bIntl.Collator
RulesLanguage collationUTF-16 code unitsSame as localeCompare (reusable)
ResultNumber (<0 / 0 / >0)Booleancompare(a, b) number
locales / optionsYesNoYes (set once)
Best forOne-off compares / small sortsQuick code-unit checksSorting large lists

Examples Gallery

Examples follow MDN String.localeCompare() patterns. Use View Output or Try It Yourself for each case. Outputs use Math.sign where engines may differ on exact integers.

📚 Getting Started

Read before / after / equal from the return value.

Example 1 — Basic localeCompare()

MDN-style: negative, positive, and zero.

JavaScript
Math.sign("a".localeCompare("c"));           // -1  (before)
Math.sign("check".localeCompare("against")); // 1   (after)
"a".localeCompare("a");                      // 0   (equal)

// In sort callbacks, return the number directly:
["c", "a", "b"].sort((x, y) => x.localeCompare(y));
// ["a", "b", "c"]
Try It Yourself

How It Works

Math.sign normalizes any negative/positive engine result to -1 / 1. For sort, pass the raw localeCompare result — sort only cares about the sign.

Example 2 — Accents and sensitivity: "base"

MDN demo: treat accents and case as the same base letters.

JavaScript
const a = "réservé"; // accents, lowercase
const b = "RESERVE"; // no accents, uppercase

Math.sign(a.localeCompare(b));  // 1  (not equal by default)

a.localeCompare(b, "en", { sensitivity: "base" });
// 0  — same base letters
Try It Yourself

How It Works

sensitivity: "base" ignores case and accents for equality / ordering. Other values include "accent", "case", and "variant" (see Intl.Collator docs).

📈 Practical Patterns

Locales, sorting lists, and numeric string order.

Example 3 — Different Languages, Different Order

MDN note: German and Swedish disagree about "ä".

JavaScript
Math.sign("ä".localeCompare("z", "de")); // -1  (ä before z in German)
Math.sign("ä".localeCompare("z", "sv")); // 1   (ä after z in Swedish)

"ä".localeCompare("a", "de", { sensitivity: "base" }); // 0
Math.sign("ä".localeCompare("a", "sv", { sensitivity: "base" })); // 1
Try It Yourself

How It Works

Always pass the UI language (or a short fallback list) when order must match what users expect in that language.

Example 4 — Sort an Array

MDN pattern: French sort that ignores punctuation.

JavaScript
const items = ["réservé", "Premier", "Cliché", "communiqué", "café", "Adieu"];

items.sort((a, b) => a.localeCompare(b, "fr", { ignorePunctuation: true }));
// ['Adieu', 'café', 'Cliché', 'communiqué', 'Premier', 'réservé']
Try It Yourself

How It Works

The comparator returns the localeCompare number so sort can place each pair. For large lists, create one Intl.Collator("fr", { ignorePunctuation: true }) and reuse .compare.

Example 5 — Numeric Sorting

MDN pattern: make "2" sort before "10".

JavaScript
Math.sign("2".localeCompare("10"));  // 1  ("2" after "10" by default)

Math.sign("2".localeCompare("10", undefined, { numeric: true })); // -1

Math.sign("2".localeCompare("10", "en-u-kn-true")); // -1  (Unicode extension)

["10", "2", "1"].sort((a, b) =>
  a.localeCompare(b, undefined, { numeric: true })
);
// ["1", "2", "10"]
Try It Yourself

How It Works

Without numeric, strings compare digit-by-digit, so "10" can come before "2". With numeric: true, embedded numbers compare as numbers.

🚀 Common Use Cases

  • Sorting UI lists — names, titles, countries in the user’s language.
  • Case- / accent-insensitive equalitysensitivity: "base" and check for 0.
  • Natural number order in stringsnumeric: true for "item2" vs "item10".
  • Locale-specific rules — pass "de", "sv", "fr", etc.
  • Large sorts — prefer a reused Intl.Collator.
  • Not for simple contains checks — use includes() / indexOf() instead.

🧠 How localeCompare() Decides Order

1

Receive the other string

Coerce compareString; read optional locales and options.

Input
2

Apply collation rules

Use language-aware ordering (via Intl.Collator when available).

Collate
3

Honor sensitivity / numeric / …

Options can ignore accents, treat digits as numbers, and more.

Options
4

Return a sort number

Negative, zero, or positive — perfect for Array.sort.

📝 Notes

  • Do not rely on exact -1 / 1 — only the sign (or 0) is guaranteed.
  • Pass locales when the UI language must control sort order.
  • Omitting the compare string (or passing undefined) compares against "undefined".
  • For many comparisons with the same rules, reuse Intl.Collator.
  • < / > are not locale-aware — prefer localeCompare for human-facing order.
  • Results can still differ slightly across engines for edge cases; lock locales + options for consistency.

Browser & Runtime Support

String.prototype.localeCompare() is Baseline Widely available. The locales and options arguments are supported in modern engines via Intl.

Baseline · Widely available

String.localeCompare()

Safe for production sorting and comparisons. Prefer Intl.Collator when sorting large arrays with the same options.

Universal Widely available
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
localeCompare() Excellent

Bottom line: Use String.localeCompare() for locale-aware order. Check the sign of the result (not exact -1/1), pass locales when language matters, and reuse Intl.Collator for big sorts.

Conclusion

String.prototype.localeCompare() compares strings with language-aware rules and returns a number for sorting: negative, zero, or positive. Use locales and options for accents, case, and numeric order — and reach for Intl.Collator when you sort large lists often.

Continue with includes(), indexOf(), or the String methods hub.

💡 Best Practices

✅ Do

  • Use < 0 / > 0 / === 0 (or Math.sign)
  • Pass the UI language in locales when order matters
  • Use { numeric: true } for natural number order in strings
  • Reuse Intl.Collator for large sorts
  • Return localeCompare directly from sort comparators

❌ Don’t

  • Assert exact -1 or 1 in tests
  • Assume < / > match dictionary order
  • Forget accents/case when you meant sensitivity: "base"
  • Call localeCompare with heavy options millions of times without a collator
  • Omit the compare string and expect a useful default

Key Takeaways

Knowledge Unlocked

Five things to remember about String.localeCompare()

Locale-aware sort numbers — negative, zero, or positive.

5
Core concepts
🌐 02

Locales

language tags

i18n
03

Options

sensitivity / numeric

Tune
📈 04

Sort

Array.sort helper

Pattern
📄 05

Mutates

no

Immutable

❓ Frequently Asked Questions

String.prototype.localeCompare(compareString, locales?, options?) returns a number that tells you the sort order: negative if this string comes before compareString, positive if after, and 0 if they are equivalent for that locale/options.
No. The specification only requires a negative or positive number (or 0). Some engines return -1/1; others may return -2/2. Use < 0, > 0, or Math.sign().
When sort order must match a language (for example German vs Swedish) or when you need sensitivity, numeric sorting, or ignorePunctuation. Without them, the host locale is usually used.
Operators like < compare UTF-16 code units. localeCompare uses language-aware collation rules (and can ignore case/accents with options).
For sorting many strings, yes. Create one Intl.Collator and reuse its compare method — faster than calling localeCompare on every pair with the same locales/options.
No. Strings are immutable. localeCompare only reads and returns a number.
Did you know?

You can enable numeric collation with a Unicode locale extension instead of an options object: "en-u-kn-true". That is the same idea as { numeric: true }, packed into the language tag.

More String Methods

Return to the hub for slice, trim, replace, and more.

String methods hub →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful