<!-- mobian-agent-page publisher="dailydev" canonical="https://daily.dev/posts/how-to-write-javascript-sort-comparators-e4ugbgw53" -->

---
title: How to write JavaScript sort comparators | daily.dev
description: A deep dive into JavaScript sort comparators covering the return value contract (negative/zero/positive), the default string-sort trap, proper string sorting...
canonical: https://daily.dev/posts/how-to-write-javascript-sort-comparators-e4ugbgw53
twitter:card: summary_large_image
twitter:site: @dailydotdev
og:type: website
og:site_name: daily.dev
og:title: How to write JavaScript sort comparators | daily.dev
og:description: A deep dive into JavaScript sort comparators covering the return value contract (negative/zero/positive), the default string-sort trap, proper string sorting...
og:url: https://daily.dev/posts/how-to-write-javascript-sort-comparators-e4ugbgw53
og:image: https://api.daily.dev/og/posts/e4UGbGw53.png
og:image:alt: How to write JavaScript sort comparators
og:image:width: 1200
og:image:height: 630
og:locale: en
---

> ## Documentation Index
> Fetch the complete documentation index at: https://daily.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# How to write JavaScript sort comparators

**[Flavio Copes](https://daily.dev/sources/flaviocopes)** · 5 min read · 7 upvotes · 3 comments

## Summary

A deep dive into JavaScript sort comparators covering the return value contract (negative/zero/positive), the default string-sort trap, proper string sorting with localeCompare and its options (numeric, sensitivity), multi-key sorting patterns using early returns or the || shortcut, sort stability since ES2019, performance optimization with Intl.Collator, and handling null/undefined values to avoid NaN breaking the comparator contract.

## Full article

daily.dev links to this article rather than hosting it. Read it at the original source: <https://flaviocopes.com/javascript-sort-comparators>

## Questions this post answers

### Why does calling array.sort() without a comparator sort numbers incorrectly in JavaScript?

Without a comparator, sort() converts every element to a string and compares them lexicographically, so numbers like 105 and 61 get compared as '105' and '61', with '1' sorting before '6'. This produces results like [105, 61, 88, 92] instead of numeric order. Always pass an explicit comparator such as (a, b) => a - b when sorting numbers.

_Debugging unexpected sort output in javascript is a common trap developers track down on daily.dev._

### How do I sort an array of strings properly in JavaScript instead of using basic comparison operators?

Use localeCompare(), which returns negative, zero, or positive like a proper comparator and compares strings the way a human would, avoiding issues where uppercase letters and accented characters sort incorrectly with raw < and > operators. Passing { numeric: true } as an option makes 'file2.txt' sort before 'file10.txt' instead of comparing digits character by character.

_Choosing the right string sorting approach in javascript is easier with guidance developers find on daily.dev._

### When should I use Intl.Collator instead of localeCompare() for sorting in JavaScript?

Intl.Collator pays the locale setup cost once by creating a reusable collator object, such as new Intl.Collator('en', { numeric: true }), whose compare method can be passed directly to sort(). It produces the same results as localeCompare() with matching options but runs noticeably faster on large arrays, though for a few dozen items the difference isn't noticeable.

_Optimizing sort performance in javascript is a decision developers refine using resources on daily.dev._

## Community discussion

Top comments from developers on daily.dev.

**@allinonetools** · 2 upvotes

> The default string sort has caught me more than once 😅. Understanding the comparator contract makes sorting so much more predictable.

**@rizzdev** · 0 upvotes

> How do locale options compose across multiple sort keys?

**@alexeyzerkalenkov** · 0 upvotes

> It is well written—concise and to the point, without fluff, and in good style. Thanks for sharing!

## Similar posts on daily.dev

- [Most JavaScript Developers Get == Wrong in Interviews \(Not Because It's Hard\)](https://daily.dev/posts/most-javascript-developers-get-wrong-in-interviews-not-because-it-s-hard--i6iheuzwh) · Medium · 1 upvotes · 0 comments
- [What's actually new in JavaScript \(and what's coming next\)](https://daily.dev/posts/what-s-actually-new-in-javascript-and-what-s-coming-next--nffnrggpd) · Neciu Dan · 66 upvotes · 5 comments
- [C\# String Comparison: Equals, OrdinalIgnoreCase, StringComparer, and Culture Pitfalls](https://daily.dev/posts/c-string-comparison-equals-ordinalignorecase-stringcomparer-and-culture-pitfalls-na8wbs2pq) · We Are .NET · 0 upvotes · 0 comments
- [JavaScript ES2026 is Less About New Syntax — and More About Writing Better Code](https://daily.dev/posts/javascript-es2026-is-less-about-new-syntax-and-more-about-writing-better-code-0zsgaegpc) · Medium · 1 upvotes · 0 comments
- [Arrays, objects… now ‘composites’? – Frontend Masters Blog](https://daily.dev/posts/arrays-objects-now-composites-frontend-masters-blog-wmi32ct9u) · Frontend Masters · 8 upvotes · 0 comments

---

Tags: [#javascript](https://daily.dev/tags/javascript)

[View this post on daily.dev](https://daily.dev/posts/how-to-write-javascript-sort-comparators-e4ugbgw53)

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://daily.dev/#organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180},"sameAs":["https://twitter.com/dailydotdev","https://github.com/dailydotdev","https://www.linkedin.com/company/daily-dev-ltd"]},{"@type":"WebSite","@id":"https://daily.dev/#website","url":"https://daily.dev","name":"daily.dev","publisher":{"@id":"https://daily.dev/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://daily.dev/search?q={search_term_string}"},"query-input":"required name=search_term_string"}}]}
{"@context":"https://schema.org","@type":"TechArticle","headline":"How to write JavaScript sort comparators","url":"https://daily.dev/posts/how-to-write-javascript-sort-comparators-e4ugbgw53","mainEntityOfPage":{"@type":"WebPage","@id":"https://daily.dev/posts/how-to-write-javascript-sort-comparators-e4ugbgw53"},"datePublished":"2026-07-30T07:49:02.817Z","dateModified":"2026-09-13T19:17:42.306Z","description":"A deep dive into JavaScript sort comparators covering the return value contract (negative/zero/positive), the default string-sort trap, proper string sorting...","image":"https://media.daily.dev/image/upload/f_auto,q_auto/v1/posts/7219243bb6b6113ecc90bd933965a4ef?_a=AQAEuop","thumbnailUrl":"https://media.daily.dev/image/upload/f_auto,q_auto/v1/posts/7219243bb6b6113ecc90bd933965a4ef?_a=AQAEuop","isAccessibleForFree":true,"articleSection":"Flavio Copes","inLanguage":"en","publisher":{"@type":"Organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180}},"author":{"@type":"Organization","name":"Flavio Copes","logo":"https://media.daily.dev/image/upload/t_logo,f_auto/v1/logos/1f2dbd275797411bbd37bfdaaf0951a9","url":"https://daily.dev/sources/flaviocopes"},"commentCount":3,"discussionUrl":"https://daily.dev/posts/how-to-write-javascript-sort-comparators-e4ugbgw53","interactionStatistic":[{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":7},{"@type":"InteractionCounter","interactionType":{"@type":"CommentAction"},"userInteractionCount":3}],"keywords":"javascript","timeRequired":"PT5M"}
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://daily.dev"},{"@type":"ListItem","position":2,"name":"Flavio Copes","item":"https://daily.dev/sources/flaviocopes"},{"@type":"ListItem","position":3,"name":"How to write JavaScript sort comparators"}]}
{"@context":"https://schema.org","@type":"WebPage","@id":"https://daily.dev/posts/how-to-write-javascript-sort-comparators-e4ugbgw53","comment":[{"@type":"Comment","text":"The default string sort has caught me more than once 😅. Understanding the comparator contract makes sorting so much more predictable.","datePublished":"2026-07-31T03:07:29.870Z","url":"https://daily.dev/posts/e4UGbGw53#c-Le2K7WFLM","author":{"@type":"Person","name":"AllInOneTools","url":"https://daily.dev/allinonetools","image":"https://media.daily.dev/image/upload/s--4ZT8QlF0--/f_auto/v1769790028/avatars/avatar_igzBsWloJeaegzm9bQltZ?_a=BAMAMiiu0"},"interactionStatistic":{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":2}},{"@type":"Comment","text":"How do locale options compose across multiple sort keys?","datePublished":"2026-08-01T05:55:29.912Z","url":"https://daily.dev/posts/e4UGbGw53#c-1sZOKS5WD","author":{"@type":"Person","name":"Andrew","url":"https://daily.dev/rizzdev","image":"https://media.daily.dev/image/upload/s--35vRfXAA--/f_auto/v1785413727/avatars/avatar_fQ7ttCKtPuu6tDvcgQXv5?_a=BAMAMicg0"}},{"@type":"Comment","text":"It is well written—concise and to the point, without fluff, and in good style. Thanks for sharing!","datePublished":"2026-07-31T15:03:33.246Z","url":"https://daily.dev/posts/e4UGbGw53#c-tCmP6i7hB","author":{"@type":"Person","name":"Alexey Zerkalenkov","url":"https://daily.dev/alexeyzerkalenkov","image":"https://lh3.googleusercontent.com/a/ACg8ocKQBwPwaHC4XrPy0rniDybogCxlwDp7QCLkbwsqNRQSFhqDIlIf=s96-c"}}]}
{"@context":"https://schema.org","@type":"FAQPage","@id":"https://daily.dev/posts/how-to-write-javascript-sort-comparators-e4ugbgw53#faq","mainEntity":[{"@type":"Question","name":"Why does calling array.sort() without a comparator sort numbers incorrectly in JavaScript?","acceptedAnswer":{"@type":"Answer","text":"Without a comparator, sort() converts every element to a string and compares them lexicographically, so numbers like 105 and 61 get compared as '105' and '61', with '1' sorting before '6'. This produces results like [105, 61, 88, 92] instead of numeric order. Always pass an explicit comparator such as (a, b) => a - b when sorting numbers. Debugging unexpected sort output in javascript is a common trap developers track down on daily.dev."}},{"@type":"Question","name":"How do I sort an array of strings properly in JavaScript instead of using basic comparison operators?","acceptedAnswer":{"@type":"Answer","text":"Use localeCompare(), which returns negative, zero, or positive like a proper comparator and compares strings the way a human would, avoiding issues where uppercase letters and accented characters sort incorrectly with raw < and > operators. Passing { numeric: true } as an option makes 'file2.txt' sort before 'file10.txt' instead of comparing digits character by character. Choosing the right string sorting approach in javascript is easier with guidance developers find on daily.dev."}},{"@type":"Question","name":"When should I use Intl.Collator instead of localeCompare() for sorting in JavaScript?","acceptedAnswer":{"@type":"Answer","text":"Intl.Collator pays the locale setup cost once by creating a reusable collator object, such as new Intl.Collator('en', { numeric: true }), whose compare method can be passed directly to sort(). It produces the same results as localeCompare() with matching options but runs noticeably faster on large arrays, though for a few dozen items the difference isn't noticeable. Optimizing sort performance in javascript is a decision developers refine using resources on daily.dev."}}]}
```

