Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
JavaScript

JavaScript: Fix Array.prototype.sort() Silently Mutating the Original Array When You Meant to Sort a Copy

- 15.10.26 - ErcanOPAK

⚡ The Sort That Rearranged the Wrong Array

Array.prototype.sort() sorts the array in place and returns a reference to that same array – it does not hand back a new, independently sorted copy. Code that writes const sorted = items.sort(…) while still holding onto items elsewhere, expecting items to keep its original order, is actually mutating items itself; sorted and items are the exact same array object afterward, and anything else in the program that already had a reference to items sees it reordered too.

🔎 The Problem

const scores = [42, 7, 93, 15];
const originalOrder = scores; // same reference, not a copy

function getLeaderboard(list) {
  // Looks safe - returns a new "sorted" variable:
  const sorted = list.sort((a, b) => b - a);
  return sorted;
}

const leaderboard = getLeaderboard(scores);

console.log(leaderboard);    // [93, 42, 15, 7]
console.log(scores);         // [93, 42, 15, 7]  <- mutated!
console.log(originalOrder);  // [93, 42, 15, 7]  <- "changed"
                              // too, because it was always
                              // the same array under a
                              // different name

✅ Fix: Sort a Copy When the Original Order Has to Survive

  • Sort a copy when the original order needs to survive: […items].sort(…) or items.slice().sort(…) both create a new array first, leaving the original untouched by the in-place sort that follows.
  • Use Array.prototype.toSorted() – the newer, non-mutating sibling of sort(), available in modern engines – when you can rely on it; it returns a new sorted array and leaves the original exactly as it was, with no spread or slice needed.
  • Treat any array passed into a function as something you shouldn’t mutate by default unless the function’s name or docs say otherwise – a function called getLeaderboard or formatForDisplay reads like it should be read-only, and sort() silently breaks that assumption for every caller.

🚨 Why This Is Dangerous

  • Everything downstream of the mutation keeps working – the array is still a perfectly valid array, just in a different order, so nothing throws and nothing logs an error; the bug only surfaces as some other part of the program that shares the same array now showing things in the wrong order.
  • It’s one of the most commonly miscredited ‘pure’ methods in JavaScript precisely because its siblings map, filter, and slice all return new arrays – sort() (and reverse() and splice()) are the odd ones out that mutate in place, and muscle memory from the others leads straight into this.

sort() never promised you a new array – it promised you the same array, rearranged, and handed back to you as if that were a kindness.

— JavaScript Tip

Related posts:

AJAX — Network Tab Lies About Timing

AJAX — Network Tab Lies About Timing

JavaScript: Fix a ResizeObserver Callback Firing in an Infinite Loop Because It Resizes the Very Ele...

JavaScript: Fix a ResizeObserver Callback Firing in an Infinite Loop Because It Resizes the Very Ele...

AJAX Requests Canceled on Page Navigation

AJAX Requests Canceled on Page Navigation

Views: 13

Post navigation

SQL Server: Fix ON DELETE CASCADE Silently Deleting Rows Several Tables Away Through a Chain of Foreign Keys You Forgot About
ASP.NET Core: Fix a ProblemDetails Response That Silently Drops Custom Extension Members Because of Case-Sensitive JSON Property Names

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (980)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com