Simplify Your JavaScript Code with New Array Methods

Simplify Your JavaScript Code with New Array Methods

ยท

2 min read

Hi everyone,

In this blog, I will introduce you to some recently added JavaScript array methods. These methods are designed to simplify and clean up your code, making it more efficient and readable. Let's explore these methods one by one.

  • At

  • with

  • toReversed

  • toSpliced

  • toSorted

So without further ado, let's dive right in!

Array 'At' method:

The at the method allows you to easily access the last element of an array without using the traditional arr[arr.length-1] syntax. Here's an example:

const arr = [1,2,3]
console.log(arr.at(-1))// arr.at(index)
// Output: 3

Array 'with' Method:

The with the method simplifies changing the value at a specific index in an array without modifying the original array. Here's an example:

const arr1 = [1, 2, 3];
const arr2 = arr1.with(0, 4); // Changing value at index 0 to 4

console.log('original', arr1); // Output: [1, 2, 3]
console.log('changed', arr2);  // Output: [4, 2, 3]

Array 'toReversed' Method:

The toReversed the method allows you to obtain a reversed version of the array without modifying the original array. Here's an example:

const arr1 = [1, 2, 3];
const arr2 = arr1.toReversed();

console.log('original', arr1); // Output: [1, 2, 3]
console.log('changed', arr2);  // Output: [3, 2, 1]

Array 'toSpliced' Method:

The toSpliced the method behaves similarly to the traditional splice method, but it returns the changed array without mutating the original array. Here's an example:

const arr1 = [1, 2, 3];
const arr2 = arr1.toSpliced(0, 1, 4); // Removing 1 element at index 0 and adding 4

console.log('original', arr1); // Output: [1, 2, 3]
console.log('changed', arr2);  // Output: [4, 2, 3]

Array 'toSorted'

The toSorted the method returns a sorted version of the array without modifying the original array. Here's an example:

const arr1 = [1, 3, 2];
const arr2 = arr1.toSorted();

console.log('original', arr1); // Output: [1, 3, 2]
console.log('changed', arr2);  // Output: [1, 2, 3]

I hope this blog provides you with a good understanding of these new JavaScript array methods. Keep in mind that compatibility may vary depending on the browser you are using, but these methods are gaining widespread support. For further details, refer to the MDN documentation.

Thank you for investing your time in reading this blog, and I wish you nothing but success and happiness in your coding journey! Happy coding! ๐Ÿ˜Š๐Ÿ˜Š.

ย