15 Killer JavaScript Methods You Should Know thumbnail

15 KILLER JavaScript Methods You Should Know!

Shares

JavaScript has some great built-in methods that can make your life 10 times easier! So let’s take a moment to explore my TOP 15 KILLER JavaScript methods. Let’s start this list with my favorite 3 array methods, .filter(), .map() and .reduce()…

1) .filter()

.filter() takes an array, loops through it and returns a new “filtered” array from all the elements that passed a true or false test specified in a function.

How does it work?

You start by calling .filter() on your array and passing a function as an argument. This is the functions that will run a true or false test.

The function you pass has access to 3 arguments provided by .filter(). They are the element, index an array. The only one you actually need is element.

For .filter to work you NEED to provide a variable name in the parameters of your function to represent the element.

The other arguments are optional.

Next, your function takes the element passed and performs a true or false test. If the test returns true, the element is added to a new array, if not, it’s filtered out.

Make sure you return the result of your true or false test, because again, if you don’t .filter() won’t work!

It is worth noting that .filter() does NOT change the original array, instead, it returns a NEW array.

So where can it be used?

Obviously, anywhere you need the ability to filter data, this method is a no-brainer! But it’s also great for adding some searching functionality to your projects.

Example:

2) .map()

.map() works in a similar way to .filter(). It takes an array, loops through, and evokes a function on each element, then return the result in a new array.

How does it work?

First, throw .map() on the end of an array, then pass a function into its parameters.

Like.filter(), the function you pass has access to the same 3 arguments, element, index, array. But again, you only need element! So make sure you add a variable representing the element in the parameters of your function.

Now you have access to the element in your function you can do cool stuff!

If you want, you could take that element and transform it in some way.

For example, concatenating something else onto each element, perform a calculation, or grab the property values from the elements and return that in a new array.

So where can it be used?

It all comes down to the function you define, but it has a ton of use cases.

If you have an array of objects, you could tell the function to extract the values of a particular property i.e. person.age. That would give you a list of ages. Or you could change all the text in an array to uppercase.

Personally, I find the method really useful when working with React. It enables me to take data from an array, pass it into a component, then return an array of components with the updated data. Lifesaver!

In case my explanation wasn’t quite up to scratch, I recommend checking out this post, written by a buddy of mine, Tom Rasmussen (aka @tallestthomas over on Instagram).  

Example:

3) .reduce()

.reduce(), like .map() and .filter() loops over an array. But instead of return a new array, it takes a function in order to reduce the array to a single value.

How does it work?

The setup is similar to .map() and .filter(), but for one added bonus.

.reduce() takes a function as an argument, and that function has access to the 4 arguments. Not 3 like .map() and .filter().

Those arguments are (accumulator, element, index, array). But only the element” and accumulator are required to make this puppy work.

The accumulator represents the accumulated total or result returned from the function you pass in. The element represents the current element.

Your function should take the accumulator and element, perform an operation, and return a single value. That value will now be stored as the accumulator. You will see an example below.

In addition to the function argument, you can also pass a second argument to represent the initial value at which your callback function should start totaling from.

So where can it be used?

Well, one thing you could do is total up an array of numbers. This is often quite common. If you have an array of products and need to total up the price, using .reduce just makes sense!

But you could also use it to find an average by dividing the total (accumulator) by the length of the array.

Example:

4) .forEach()

.forEach() is a simpler and more readable way to write your standard for loop. It works by taking a function and calling it on each item in an array.

I know what your thinking. This sounds awfully familiar to .map(). Yes, it does, except for one big difference…

.forEach() mutates (changes) the original array it’s call on, whereas .map() returns a new array.

This makes them both better for different things, which I’ll cover in a seconds.

How does it work?

.forEach() takes a function, and that function requires you to provide one main argument…the element.

In your function, you can grab the element passed and do something to it. Whether that’s updating the element or changing it.

.forEach() will now loop over your array and apply that function to each element. The same way a normal for loop would! However, in a cleaner more readable way!

So where can it be used?

I mentioned that .forEach() and .map() seem very similar. So how do you know which one to use?

Whenever you need to change or interact with the original data in someway, .forEach() is what you need. But, if you want to keep the original data intact, use .map().

For example, .forEach() would be ideal if you needed to update the properties of an array of objects. However, if you need to pass data from an array, or create a slightly mutated copy, that’s when you would reach for .map().

But really, other than that, you can use .forEach() in the same way you would use a traditional for loop.

Example:

5) .indexOf()

.indexOf() can actually come in two forms String.prototype.indexOf() and Array.prototype.indexOf().

Both basically do the same thing but on different data types. But I wanted to mention both so there is no confusion when you come to search for this method in future.

It’s a simple method, which returns the index of an element in a structure. Whether that’s a String or an Array.

How does that work for each?

.indexOf() called on an array will take an argument like a number, and return the index where that number first appears in the array.

.indexOf() called on a string will take an argument like a character, and return the index where that character first appears in the string.

Fairly straightforward right?!

You should also know that .indexOf() also gives you the option to start searching from a particular point. By passing a number as the second argument you can effectively say “start searching from this index”.

Side note! .indexOf() has a twin method, .lastIndexOf(). This one does very much the same, except it returns the index of the last occurrence.

So where can it be used?

.indexOf() is a pretty handy method whenever you need to quickly find the position of an item. But it can also be used to return all occurrences of an item.

Example:

6 & 7) .some() and .every()

I’ve paired these two together because they are almost identical.

Both of them are array methods that return a Boolean. Both expect a function that runs a true or false test. However…both DON’T return the same thing!

.every() will only return true if ALL test’s on its elements pass, whereas .some() will return true if just ONE test passes.

So how does it work?

In both cases you pass in a function, that function takes the array element as an argument. In that function, you write a true or false test to be performed on each element.

The methods will then loop over your array an run that test on each element. The result you get back will vary depending on whether you are using .some() or .every().

So where can it be used?

Both of these methods are really good for doing some quick validation. For example, checking if data in an array matches the minimum criteria. Or checking if the data is valid i.e. doesn’t contain any undefined or nil values.

Example:

8, 9, 10) Object.keys(), Object.values(), Object.entries()

These three are pretty interesting object methods. They all allow you to reach into an object and pull out sets of data and return it in an array.

Each one will return a different data set so it will depend on your need as to which one you use.

So how do they work?

Object.keys() will return the keys from an object.

Object.values() will return the values assigned to those keys.

Object.entries() will return an array of arrays for each key value pair.

And to use them all you do is type “Object.keys()”, then pass the object into the parameters. Simple.

So where can it be used?

These methods really shine when working with data. Sometimes you may have the need to translate data in an object to an array. It may be that the data is better suited to an array, or you want to take advantage of some of the cool array methods above!

Example:

11) Object.freeze()

You can probably guess what Object.freeze() does simply by the name. But just to clarify Object.freeze() freezes an object, essentially making the object and its properties immutable (unable to be changed).

How does it work?

It’s easy enough, just write “Object.freeze()”, passing in the object you want to freeze. Then the method does its magic and returns the frozen object.

To access your new frozen object you will need to save it into a variable.

Now if you try to modify the frozen object an error should be thrown and the object won’t be changed.

Object.freeze() can also be used to freeze and array for instances when you want your array to be immutable.

So where can it be used?

The method is built for those instances when you don’t want the integrity of your data to be compromised.

For example, if your application is going to be accessible to third parties, and any change to the data may cause unwanted behavior.

Example:

12) .includes()

.includes() is a quick an easy method you can use on a string or array to find out if it contains a certain bit of data.

So how does it work?

There’s really not a lot to it. You simply call .includes() on your array or string, pass in the thing your looking for, then BOOM! Either true or false is returned.

So where can it be used?

Like .some() and .every(), this method is a quick and dirty way of validating some data. If you need to quickly check an element .includes() provides a quick a simple solution.

Example:

13) Array.from()

Array.from() has some petty cool tricks up its sleeve!

It has the ability to take anything “array-like”, which has a length, or is iterable, then creates a new array from it.

So how does it work?

To use it just call Array.from(), then pass in the thing you want to creates an array from, and you’re done.

Besides the “array-like” thing you are passing in, Array.from() can take a second argument, which is a map function.

Now, I already covered the map function earlier so I’ll just briefly summarize. The map function iterates over the array, grabbing the element, doing something with it, then returning it in a new array.

So where can it be used?

Here’s a little trick you can do with Array.from(). You can pass it a single object with a length property. Whatever value you set the length property, that will be the length/size of the array. Then you can use the map function as the second argument to populate that array.

Another cool thing you can do with Array.from() is to convert a collection of HTML tags, like a list of div’s or li’s, to an array. Now those div’s are in an array you can do all those awesome array things you like to do!

Example:

This second example produces the same result as above. HOWEVER, I have passed an object with a length property to designate the size/length of the array. Then uses the map function as a second argument to populate that array with numbers 1 – 5.

14) The Spread Operator

This isn’t actually a method but it does some really neat things so I’m just going to include it anyway.

The Spread Operator allows the contents of an array or object to be expanded out in places where multiple variables are expected.

Does that sound a bit complex? Don’t worry, I’ll explain and show you some examples.

So how does it work?

The Spread Operator is actually just 3 dots “…” followed by an iterable variable name, such as an array or object. So in actual fact, it would look something like this “…myArray”.

What that simple line is doing is taking all the elements from “myArray” and throwing them out in the open.

Have you ever tried to concatenate two arrays by doing something like “[1, 2, 3, arrayNumbers]”? What happens? Well, it just ends up putting an array within another array, which isn’t what you want (I’m assuming).

However, with the Spread Operator, you can concatenate two arrays simply by typing “[1, 2, 3, …arrayNumbers]”. The contents of “arrayNumbers” will now be “spread” into the rest of the array.

The same can be done for key-value pairs in an object.

So where can it be used?

As I mentioned, the Spread Operator is great for combining objects or arrays. You can also use it as a quick and easy way to destructure an object.  If you don’t know what destructuring is, check out this great article from Wes Bos.

For those learning or working with Redux, the Spread Operator is great when writing your reducers to update your applications state. Check out the Redux documentation to see how that works.

Example:

15) Rest Parameters

Rest Parameters looks very similar to the Spread Operator, but they are both very different!

With Rest Parameters, you can essentially represent an infinite amount of function arguments.

So how does it work?

Again, like Spread, you use the 3 dots followed by a variable name i.e. “…myArguments”.

When you actually come to write a function you simply state any arguments you know you need, followed by “…myArguments”. Then “…myArguments” will take the rest of the arguments, gobble them up, and collapses them into an array.

The key thing to note here is now “myArguments” is an array and so should be treated like an array in the function you write.

It’s easy to get confused between Spread and Rest because they look the same. The defining difference is Rest takes an undefined amount and collapses it into an array. Whereas Spread takes a structure like an array and does the reverse by expanding it out.

So where can it be used?

Rest is very handy when you want to create a variadic function.

A variadic function is a function that accepts any number of arguments. For example, you may want to join or concatenate an undefined amount strings, characters or numbers.

In this case, using Rest to create a variadic function is perfect!

Example:

I hope you enjoyed learning about these awesome methods and they help you in your future JavaScript endeavours!

Feature image designed by Freepik

Sharing is caring!

About the Author Owen

Creator of Code Dad, father and self-taught programmer. My mission is to balance life, work, family, all while learning to code, and hopefully help others who want to do the same.

follow me on: