In this tutorial, you will learn about some essential functions that you will need to master in order to become a Javascript ninja 🐱👤 Tasks like getting data from an API and displaying it on a page, is web development 101 these days. This means that you will be consistently having to handle collections of data. When dealing with collections within your Javascript application, your aim should be to write easy to understand code (declarative code). In an ideal world, you should only be creating pure functions. A pure function is simply a fancy term, for writing a function that does not mutate/change your applications state in any way. In this tutorial, I will cover 10 javascript function that you can use when working with collections. For each example, I will give you a quick code snippet you can copy from. I will also tell you which ones mutate state (ones to avoid) and which ones do not (ones to use), so let us get at it!
foreach()
The foreach()
function is a programmers class function. foreach()
allows you to loop over all of the items in the array:
✔️ foreach()
does not mutate state
includes()
The include()
function checks if the array includes a predicate that you can pass into the function:
✔️ includes()
does not mutate state
filter()
This filter()
function creates a new array from an old array, based on some filtering logic that you apply onto it:
✔️ filter()
does not mutate state
map()
The map()
function creates a new array by calling the provided function in every element:
✔️ map()
does not mutate state
reduce()
The reduce()
function applies an accumulator and each element in the array (from left to right) to reduce it to a single value. reduce()
is really powerful and super useful:
✔️ reduce()
does not mutate state
some()
This method checks if at least one of the array’s items matches the condition. If so, it returns true
otherwise false
:
✔️ some()
does not mutate state
every()
This method checks if all items within the array met the criteria. If passed, it returns true
otherwise false
:
✔️ every()
does not mutate state
sort()
This function can be used to arrange/sort a collection in either ascending or descending order:
❌ sort()
does mutates state
To fix this you should use it like this:
Array.from()
This changes all things that are array-like, or, iterable into a true array. This function is useful when working with the DOM. Converting elements into an array so that you can use other array methods like .reduce()
, map()
, filter()
and so on them:
Working with the DOM
✔️ from()
does not mutate state
Array.of()
Array.of()
creates an array from every argument passed into it.
✔️ of()
does not mutate state
As you can see there are a number of functions that are safe to use. Try to avoid functions like array.splice()
, array.push()
and array.ushift()
which mutate state. As you have seen using sort()
, it is still possible to structure to protect it from mutating state. I definitely recommend you do this. Happy Coding 🤘