Understanding the .at() and .with() Methods in JavaScript

JavaScript continuously evolves, providing new methods to make our code more readable and efficient.

Among these recent additions, .at() and .with() are two methods that can simplify certain operations on arrays and strings.

.at()

The .at() method is used to access a specific element in an array by its index. It returns the value of the element at the specified index. Here's an example:

const colors = ['red', 'green', 'blue'];
const element = colors.at(1);
console.log(element); // Output: 'green'

Accessing the last element of an array is a common operation.

array[array.length - 1]; // What we could do before
array.at(-1); // Easier and more intuitive with .at()

What I like the most about .at() method is that it is a method that improves readability a lot. Let's compare .slice(), .length and .at() to perform the same operation.

const animals = ["panda", "zebra", "penguin"];

// with slice()
const animal = animals.slice(-2, -1); // 'zebra'

// with the length property
const animal = animals[animals.length - 2]; // 'zebra'

// with at()
const animal = animals.at(-2); // 'zebra'

.with()

The .with() method is used to replace a specific element in an array with a new value. It returns a new array with the modified element. Here's an example:

const colors = ['red', 'green', 'blue'];
const modifiedColors = colors.with(0, 'yellow');
console.log(modifiedColors); // Output: ['yellow', 'green', 'blue']

As you can guess, .with() is a method that does not mutate the original array, but returns a new array with the modified element.

It allows to replace some usages of .map(), for example:

const users = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
    { id: 3, name: 'Bob' }
];
// Replace the name of a specific user
function getUpdatedUsers(index, name) {
    return users.map((user, i) => ({
        ...user,
        name: i === index ? name : user.name
    }));
}
// Version with .with()
function getUpdatedUsersWithWith(index, name) {
    return users.with(index, { ...users[index], name });
}

Conclusion

The .at() and .with() methods are welcome additions to JavaScript, making operations on arrays and strings more readable and intuitive. By leveraging these new functionalities, you can write more concise and expressive code while maintaining immutability where needed!