From 0d889a492391968c55ce1a9ebc32781682284c1f Mon Sep 17 00:00:00 2001 From: AlexandrosNt Date: Thu, 21 May 2026 16:17:23 +0300 Subject: [PATCH] feat: add toSorted() explanation and examples. - Briefly explains the concept of immutability and why mutating original data is avoided in modern JS. - Introduce` toSorted()` as the modern alternative to `sort()` . - Includes a runnable code block (`js run`) demonstrating how the original array remains untouched compared to the new sorted array. --- 1-js/05-data-types/05-array-methods/article.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/1-js/05-data-types/05-array-methods/article.md b/1-js/05-data-types/05-array-methods/article.md index 8536459582..53a66ea19f 100644 --- a/1-js/05-data-types/05-array-methods/article.md +++ b/1-js/05-data-types/05-array-methods/article.md @@ -505,6 +505,20 @@ alert( countries.sort( (a, b) => a.localeCompare(b) ) ); // Andorra,Österreich, ``` ```` +### toSorted + +In modern JavaScript, we generally avoid mutating original data, as it can lead to unexpected side effects and bugs. Because the traditional `sort()` method modifies the array in place, a new modern method was introduced. The `toSorted()` method elegantly solves this problem by returning a completely new, sorted array, leaving the initial data safely intact. It is also more optimized than the older workaround of manually cloning the array before sorting. + +```js run +let fruits = ["Orange", "Apple", "Banana"]; + +// Use toSorted() to get a new sorted array +let sortedFruits = fruits.toSorted(); + +alert( fruits ); // Orange, Apple, Banana (safe and unmodified!) +alert( sortedFruits ); // Apple, Banana, Orange +``` + ### reverse The method [arr.reverse](mdn:js/Array/reverse) reverses the order of elements in `arr`.