ES2023 – What’s new in JavaScript?

Introduction

In this article, we’ll discuss the new JavaScript array features that were added in ES2023.

findLast and findLastIndex

Let’s say we have an array with elements:

const arr = [0, 1, 2, 3, 7];

We need to find the element with the value 7and we’re assuming it’s near the end of the array.

In the previous case, when we used find(), we would do it like this:

const arr = [0, 1, 2, 3, 7];
const res = arr.find(el => {
console.log('Поиск');
return el == 7;
})
// 5 раз будет выведено в консоли слово "Поиск"

This may be fine for small arrays, but if the array is large and you know the element is near the end, then you can use the findLast() method:

const arr = [0, 1, 2, 3, 7];
const res = arr.findLast(el => {
console.log('Поиск');
return el == 7;
})
// вывод в консоль: Поиск

In this case, the withdrawal will occur only 1 time.

Similarly, there is a findLastIndex() method that looks for an element by index.

Methods that do not change the original array

Most JavaScript array methods modify the original array instead of creating a new one. For example, this can cause problems in React when it needs to change the state and create a new array. We will look at how this is addressed in the latest version of the ES2023 specification and in JavaScript. Therefore, below we will consider new methods that allow us to avoid this.

with

Suppose we need:

Now with the with() method, we can do this much easier. We need to pass in the index on which we want to replace the element, and then the value of that element:

const a = [1, 3, 5]
const arrNew = a.with(1, 'test');
console.log(a); // вывод: [1, 3, 5]
console.log(arrNew); // вывод: [1, 'test', 5]

The with() method copies the original array, changes one element, and returns a new array with the changed element at the specified index.

toSorted

The toSorted() method sorts the elements of an array in the same way as the sort() method, but returns a new array:

const a = [2, 3, 6, 1];
const b = a.toSorted();
console.log(a) // вывод: [2, 3, 6, 1]
console.log(b) // вывод: [1, 2, 3, 6]

toReversed

The toReversed() method reverses the order of the elements in an array, just like the reverse() method, but returns a new array:

const a = [2, 3, 6, 1];
const c = a.toReversed();
console.log(a) // вывод: [2, 3, 6, 1]
console.log(c) // вывод: [1, 6, 3, 2]

toSpliced

The toSpliced() method is a copy of the splice() method, but returns a new array:

const a = [2, 3, 6, 1];
const d = a.toSpliced(0, 1);
console.log(a) // вывод: [2, 3, 6, 1]
console.log(d) // вывод: [3, 6, 1]

Similar Posts

Leave a Reply

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