惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

雷峰网
雷峰网
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
宝玉的分享
宝玉的分享
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
T
Tailwind CSS Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
IT之家
IT之家
博客园_首页
博客园 - 三生石上(FineUI控件)
博客园 - 叶小钗
Apple Machine Learning Research
Apple Machine Learning Research
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
量子位
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
人人都是产品经理
人人都是产品经理
美团技术团队
小众软件
小众软件
Jina AI
Jina AI
S
SegmentFault 最新的问题
博客园 - Franky
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
JS Crime Scene: The Misleading Array
Code Crumb · 2026-05-21 · via DEV Community

🕵️ JS Crime Scene: The Case of the Misleading Array

📹 Surveillance Footage

The full investigation is available on TikTok:

View the Evidence

The call came in early.

An application was completely misbehaving, data was leaking out of order, and the logs were a mess.

The victim?

Developer Sanity

Someone tried to sort a simple array of integers, and JavaScript decided to play by its own rules.

Let's inspect the evidence, identify the culprit, and deploy the one-line fix before production collapses entirely.


🔍 The Crime Scene Report

We found a collection of numerical values at the center of the incident.

No complex objects.

No deeply nested structures.

Just raw numbers.

Here is the exact code executed at the scene:

// The Lineup (Original Array)
const numbers = [1, 10, 2, 25, 5];

// The Attempted Sort
numbers.sort();

console.log(numbers);

// Output:
// [1, 10, 2, 25, 5]

Enter fullscreen mode Exit fullscreen mode


📋 The Expected vs. Actual Output

Intended Behavior (Math) Actual Reality (JavaScript) Status
[1, 2, 5, 10, 25] [1, 10, 2, 25, 5] ❌ Maliciously Broken

Look closely at that result.

10 comes before 2?

25 comes before 5?

Did mathematics quietly stop working overnight?

Not exactly.


🕵️‍♂️ The Culprit: UTF-16 String Sorting

When you call .sort() without providing a comparator function, JavaScript does not sort numbers mathematically.

Instead, it secretly performs a type coercion operation and converts every element into a string first.

Our innocent integers suddenly became:

  • 1"1"
  • 10"10"
  • 2"2"
  • 25"25"
  • 5"5"

Once converted to strings, JavaScript compares them character-by-character using UTF-16 code unit values.

Essentially, the engine starts sorting your numbers like dictionary words.


📖 Think of It Like a Dictionary

In a dictionary:

  • "Apple" comes before "Banana"
  • because "A" comes before "B"

JavaScript applies that exact same logic here.

For example:

  • "10" starts with "1"
  • "2" starts with "2"

Since the character "1" has a lower UTF-16 value than "2", JavaScript places "10" first.

The engine isn't malfunctioning.

It's simply following text-based sorting rules.


🛠️ The Fix: Deploying a Comparator Function

To force JavaScript to sort numerically, you must explicitly tell the engine how two values should be compared.

Here’s the proper fix:

const numbers = [1, 10, 2, 25, 5];

// Numeric Sort Fix
numbers.sort((a, b) => a - b);

console.log(numbers);

// Output:
// ✅ [1, 2, 5, 10, 25]

Enter fullscreen mode Exit fullscreen mode

One tiny comparator function.

Massive difference.


⚙️ How the Comparator Actually Works

This line:

(a, b) => a - b

Enter fullscreen mode Exit fullscreen mode

subtracts the second value from the first.

JavaScript then interprets the result.

Negative Result

If the result is negative:

2 - 5 = -3

Enter fullscreen mode Exit fullscreen mode

JavaScript understands that 2 should come before 5.


Positive Result

If the result is positive:

10 - 2 = 8

Enter fullscreen mode Exit fullscreen mode

JavaScript knows 2 should move ahead of 10.


Zero

If the result is 0, both values are considered equal, and their order remains unchanged.


💡 Pro Tip: Reverse Sorting

Need descending order instead?

Just flip the subtraction:

numbers.sort((a, b) => b - a);

Enter fullscreen mode Exit fullscreen mode

Output:

[25, 10, 5, 2, 1]

Enter fullscreen mode Exit fullscreen mode


🚨 Case Closed

Another JavaScript mystery solved.

The golden rule?

Never trust the default behavior of .sort() when working with numbers.

Always provide a comparator function if you want predictable numeric sorting behavior.

Otherwise, JavaScript will happily treat your integers like alphabetized grocery items.

And that’s how 10 ends up beating 2 in a fight it should never win.


Have you ever been burned by JavaScript's default .sort() behavior in production?

Drop your horror stories below 👇