Learn and understand ES6 Helpers, easily…
Let’s understand the ES6 helpers with examples, once and for all :)
Wait Madhav! Why are you writing this blog now, everyone knows about ES6 now, it’s an old thing buddy, write something new :/
Helper methods gained huge popularity in a very short period of time after the ES6 was introduced. Some of these helper methods already existed in some external libraries, and developers really wanted them to be native to JavaScript itself. Using helpers have many benefits like making the code more readable, reducing the number of lines of code, etc.
I do agree with you that ES6 isn’t the newest of the concepts in JS, but after ES6 the rate at which JavaScript community grew was incredible, it was so amazing.
But the fact still remains that the new developers out there still find some concepts difficult to grasp. The things introduced in ES6 like the helper methods, arrow functions, const & let, template strings, destructuring, rest and spread, etc. (according to me), are very very frequently used while developing applications using JavaScript.
Almost everyone uses these concepts in their code. Now let’s imagine this from a JS newbie’s point of view, what happens when he sees these things in a code he reads from a random GitHub repository, he must be like,
Waaait a second, I was only taught about the normal for loop,
var
for declaring variables, and what’s thisreduce()
thing for, and ohh man, what is this...rest
. What’s this promise thing? Can someone explain me what’s this fat arrow all about? Ahh man, I need help!
Ok, I know that was dramatic, let’s say our JS newbie was a drama loving guy :)
This was one of the reasons why I decided to start a new initiative in which I discuss one JS concept per day, if you are interested, please visit this GitHub repository and leave a star (I would really be happy if you do so)
So yeah, there are plenty of reasons why I chose to write a separate blog on ES6 helpers, and I think this blog is going to be useful for beginner to intermediate JavaScript developers. Plus, I am not going to limit it to ES6 Helpers, soon I’ll be releasing blogs on more concepts of JavaScript and the newest features as well. So if you still ask why should I write this blog, I’d say,
Well, why not? If writing blogs on JS concepts helps out even a single person out there, I am satisfied!
So, without any further ado, let’s start off with the ES6 Helpers ✨
What are we going to discuss today?
As the title says, we are going to discuss about the ES6 Helper methods, which are as follows —
- The
forEach
helper - The
map
helper - The
find
helper - The
filter
helper - The
every
helper - The
some
helper - The
reduce
helper
I’ll try my best to explain you these concepts with examples so that you never feel the need to go to any other source for reading about these concepts. Happy Learning!
1. The forEach
helper
TheforEach
helper function can be seen as an alternative to the regular for loop. The forEach()
method basically calls a function (called iterator function
) once for each element in the array, in order.
In simple language, the forEach method loops through each element in an array and runs a function on that particular element.
Syntax
array.forEach(function(currentValue, index, arr), thisValue)
- currentValue: Required. The value of the current element
- index: Optional. The array index of the current element
- arr: Optional. The array object the current element belongs to
- thisValue: Optional. A value to be passed to the function to be used as its “this” value.
Example 1
Since forEach
is used for iteration, let’s iterate through an array to understand the concept :)
Example 2
Let’s go through a very simple example first, Sum each element in the array.
Why forEach?
- Less Amount of Code
- More Readable
- Less Chances of error
2. The map
helper
The map()
helps to make a new array from the elements of the given array by performing some action on each element.
In simple language, The map
helper takes a function as the argument and performs that function on each element of the given array (in order of index) to create a new array without changing the original array.
Syntax
array.map(function(currentValue, index, arr), thisValue)
- currentValue: Required. The value of the current element.
- index: Optional. The array index of the current element.
- arr: Optional. The array object the current element belongs to.
Example
Form a new array which contains the square of each number of the given array
Why creating a new array is a good practise
When the code base is small, we tend to perform all the actions on the same data structure and feel free to change it easily because we know wherever it is being used, but when the code base becomes huge and we are not sure whether a given data structure is being used at other place or not, it is not good to change it directly as it might lead to some inconsistencies at the other places where it is being used
Generally, we try not to mutate any given data structure, because it’s possible that the given data structure could have been used in some other place as well and changing it might break our code.
The map
helper comes to the rescue at such places, it applies a particular function to each element in an array and returns a new array without changing the original one.
Practice questions
- Make an array of numbers that are doubles of the first array
- Take an array of numbers and convert each element into a string
- Capitalize the first letter of each name in the names array
- Given an of news headlines (take some random data), and enclose the headlines in
<h1>
tag and append them to DOM to display the news headlines
3. The find
helper
The find
helper loops through an array to look for a particular element (first occurrence), which passes the given criteria.
It runs the provided function over each element, and if the particular element passes the criteria, it is returned. If no element found, undefined
is returned.
This helper method does not change the original array.
The Drawback
The find
helper will not work when you want to find more than one occurrences, it will work only when you need the first occurrence.
Which element to choose?
In the find
helper, we pass an iterator function which iterates over all the elements of the array. The function should have a condition, and the first element which satisfies that condition is returned.
When the condition is passed, the iterator function must return true
. The element at which the iterator function returns a true
is taken to be the required element.
Syntax
array.find(function(currentValue, index, arr),thisValue)
- currentValue: Required. The value of the current element
- index: Optional. The array index of the current element
- arr: Optional. The array object the current element belongs to
- thisValue: Optional. A value to be passed to the function to be used as its “this” value
Example 1
Given an array of numbers, find the first element which is a multiple of 7
Example 2
Given an array of objects having the data of students, find the student having register number 9018
4. The filter
helper
As the name suggests, the filter
helper is used to filter out some specific elements from an array of elements.
It creates a new array from the elements of the original array which pass the given criteria.
The criteria is generally given as a condition in the iterator function.
Unlike find
helper, filter
returns an arrow of elements that pass the criteria.
Syntax
array.filter(function(currentValue, index, arr), thisValue)
- currentValue: Required. The value of the current element
- index: Optional. The array index of the current element
- arr: Optional. The array object the current element belongs to
- thisValue: Optional. The array object the current element belongs to
Example 1
Given an array of numbers, find the count of numbers greater than 100
Example 2
Extract the information of students from an array having information about people
Homework for you
- Make a vegetable shop, given the data about vegetables, their quantity and price, allow user to query the available vegetables based on quantity and budget.
- Filter out the invalid roll numbers (roll numbers which are greater than 100 or less than 0), and return the list of correct roll numbers
- Given an array of student information, find the list of students eligible for final exams based on their attendance (>75%)
- From a list of words find the words having more than 5 letters.
5. The every
helper
The every
helper is used to find whether all the elements in a given list pass a specific condition.
The condition is passed in the iterator function, and it executes that function once for each element in the list.
If, for any element, the iterator function returns false, every()
returns false. Otherwise, it returns true.
Syntax
array.every(function(currentValue, index, arr), thisValue)
- currentValue: Required. The value of the current element
- index: Optional The array index of the current element
- arr: Optional. The array object the current element belongs to
- thisValue: Optional. A value to be passed to the function to be used as its “this” value.
Example 1
When the users submit a form, suppose that all the fields are taken out in an array before submitting the form. You have to validate that every field has at least 1 character.
Example 2
Slots of people are sent for driving license test, check whether each person in a slot is 18 years or above
Homework for you
Check whether a set of numbers is
- Even
- Odd
- Prime
- Negative
- Positive
- Perfect Square
Feel free to do more, and do contribute with more examples to this repository.
6. The some
helper
The some
helper is used to find if any one or more elements in the given list, pass a specific condition.
The condition is passed in the iterator function, and it executes that function once for each element in the list.
If, for any element, the iterator function returns true, some()
returns true. Otherwise, it returns false.
Usage and syntax is similar to every
helper.
Syntax
array.some(function(currentValue, index, arr), thisValue)
- currentValue: Required. The value of the current element
- index: Optional The array index of the current element
- arr: Optional. The array object the current element belongs to
- thisValue: Optional. A value to be passed to the function to be used as its “this” value.
Example 1
Given a collection of games with mentioned least required RAM, buy the collection, if at least one of the games can run in your computer (return true/false)
Example 2
Do the same question we did in every
helper, but by using some
helper
Slots of people are sent for driving license test, check whether each person in a slot is 18 years or above
Hint: (Every person > 18) is equivalent to (no person <18).
Try to apply this hint to do this problem using some
helper instead of every
helper
Homework for you
Check whether a set of numbers has any element which is
- Even
- Odd
- Prime
- Negative
- Positive
- Perfect Square
Feel free to add more :)
7. The reduce
helper
Probably the toughest in the helpers, that’s why I kept it for the last. You might hear people saying it’s tough, but it’s not, it’s all about understanding, once you get it, you will see it’s the most flexible helper from which you can implement a lot of things.
How it works?
Let’s discuss a very simple use case, to calculate the sum of the numbers given in the array
Just like other helpers, we will call the reduce
helper on the array. Inside the reduce, we have 2 arguments,
- The iterator function
- initial value
The iterator function requires 2 values
- total
- current value
The idea is that total
will start with the initial value
(the second argument of reduce
). Along with the total
and current value
, we will perform some operations (as we need) inside the iterator function and the final value which we return from the iterator function will be used as the value of total
in the next iteration.
Ok, I know that might sound a little confusing, but reading the syntax, and the flow diagram and going through the example should make it clear.
Syntax
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
- total: Required. The initialValue, or the previously returned value of the function
- currentValue: Required. The value of the current element
- currentIndex: Optional. The array index of the current element
- arr: Optional. The array object the current element belongs to
- initialValue: Optional. A value to be passed to the function as the initial value
Flow Diagram
Example 1
Sum the numbers given in the array
Example 2
Extract the names of students in an array from student information list
Homework for you
- Multiply all elements in the given array.
- Using reduce helper, remove the repetative elements from the given array.
- A website is scraped and all the
<p>
tags are extracted in an array, preprocess the data to remove the tags and extract information. Store the extracted information in a separate array. - From a given string, make a new string which is reverse of the original one (using
reduce
helper)
That’s it! Hope you found the article helpful 😁
Feel free to reach out to me anytime if you want to discuss something :D
I would be more than happy if you send your feedbacks, suggestions or ask queries. Moreover, I love to make new friends and we can be friends, just drop me a mail.
Thanks a lot for reading till end. You can contact me in case if you need any assistance:
Email: theleanprogrammer@gmail.com
Web: http://madhavbahl.tech/
Github: https://github.com/MadhavBahlMD
LinkedIn: https://www.linkedin.com/in/madhavbahl/
Instagram: https://www.instagram.com/theleanprogrammer/