JavaScript 2023 - New Features - Part 2

ECMAScript 2023(ES14) : New Capabilities

Using toSorted() with predicate

A function can be passed as an argument to toSorted() function which identifies the sorting strategy.


/// toSorted internals with integer array 
let arr = [100,21,13,42,15,6,9];

// toSorted with - predicate - function argument
let arr2 = arr.toSorted((a,b)=> {
      console.log("a,b", a,b, typeof a);      
      return a-b;
    });

console.log("sorting - asc", arr2); // ascending

 arr2 = arr.toSorted((a,b)=> {
    console.log("a", a, b,typeof a);
    return b-a;
});

console.log("sorting dsc",arr2); // descending

The above code explains how toSorted() function works internally.The toSorted() takes 2 values from host array and compares to create the sorted array.

Using toReversed() function

The toReversed() function was introduced in es14. It doesn't change the host array but creates and returns a new reversed array.

Even a sparse array can be reversed.

//toReversed - returns a new reversed array 
let arr = [90,34,58,1,29];
let arr2 = arr.toReversed(); 
console.log("toReversed",arr,arr2);

// sparse array - undefined
let arr4 = [1,100,,200,340,,4];
let arr5 = arr4.toReversed();
console.log("toReversed",arr4,arr5);

In the above code toReversed() function returns a new array which is reversed.

The code also demonstrates how to reverse a sparse array.

Using with() function

The with() function returns an array after updating a value at the given index.

// with method - updates a value at an index - returns new array
let arr6 = arr.with(2,999);
console.log("with array:", arr6);

In the above code a new array is returned after changing value at index 2.

Complete Code Listing

//toReversed - returns a new array 
let arr = [90,34,58,1,29];
let arr2 = arr.toReversed(); // new feature
console.log("toReversed",arr,arr2);

// empty - undefined
let arr4 = [1,100,,200,340,,4];
let arr5 = arr4.toReversed();
console.log("toReversed",arr4,arr5);

// reverse() -the host is reversed
arr5 = arr4.reverse(); // 
console.log("reverse", arr4,arr5);

// with method - updates a value at an index - returns new array
let arr6 = arr.with(2,999);
console.log("with array:", arr6);

Did you find this article valuable?

Support Programming with Mahavir by becoming a sponsor. Any amount is appreciated!