In the world of modern Javascript, the concept of immutability has become increasingly popular. Instead of directly altering values within your original array, you can use the map function to create a new array with modified values. It's quite simple:
const pets = ['dog', 'cat', 'rat'];
const petsPlural = pets.map(pet => `${pet}s`);
This process may seem daunting at first, so let's break it down piece by piece.
First, let's discuss the map
function. This method is inherent to every array and essentially takes in another function as an argument. This function is then applied to each element within the original array, creating a brand new array with the altered values. The best part is that the original array (in this case, pets
) remains unchanged, ensuring the preservation of the initial values!
Next, let's examine the (...) => ...
syntax. This represents an arrow function, which was introduced in ES6 and is now widely supported by most modern browsers (excluding Safari). For example,
(arg1, arg2) => arg1 + arg2
serves as a shortened version of
function (arg1, arg2) {
return arg1 + arg2
}
Lastly, let's touch on the backtick notation. Known as a template literal, everything enclosed within ${
and }
is dynamically evaluated while anything outside remains static. For instance, when you write
`${abc}def${123}xyz`
it is essentially equivalent to
abc + 'def' + 123 + 'xyz'
Therefore, in our previous example,
`${pet}s`
translates to
pet + 's'
It's truly remarkable how effortless it becomes to comprehend this section of the code.