Five Reasons To Update Your Site

Javascript Filter is an increasingly popular method, especially when being combined with ES6 standard. So today we’re gonna dig deeper into this kind of method by JavaScript Filter Function Guide. Let’s begin!
 

Syntax Using Javascript Filter Function

let filteredList = list.filter(callback)
(We use let by ES6, those who are not familiar with this should try more)
The components are explained as below.
  • filteredList: Since filter will work with Array and return a group of Array, we need to define it as the return.
  • list: is the original array before putting to Filter()
  • callback: is a function of checking each item of the list and return either true or false
Let’s talk a little bit more about the callback function. It can receive three values as follows. Normally we only seek for the element.
function validateArray(element, index, arr) => {}

Comparison between Filter and For Loop

Apparently, you can find some similarity in the usage of Filter and For Loop. Let’s look at the example.
Below is a loop is usually seen in [removed]
let arr = [1, 2, 3, 4, 5, 6]
let even = []
for(var i = 0; i < arr xss=removed xss=removed>
The code snippet above will check every value in arr. Only values being even number are accepted and added to even.
Certainly, there is nothing wrong with the code above. Yet like traveling by motorbike and car, though they all drive you to the destination, the way they do it is different.
Here is how filter does to produce the same result.
let arr = [1,2,3,4,5,6]
let even = arr.filter(item => {
return item % 2 === 0
});
// even = [2,4,6]
Isn’t it surprising? Now there is no need to be in the loop and to add every value to one loop. When working on filter() function, all you need to do is decide what to keep and return true to those values.
Another good point of using filter is it runs smoothly on the latest web browser versions as shown by the benchmark.

Javascript Filter Function and ES6

Now that you have learned about filter(), let’s find out about the combination of this Javascript function and ES6.
Please look back to the example we have just taken above. Even we have used arrow function, we still can reduce it. We can do that because once returning value from arrow function, you can skip {} brackets in the function.
The code we have just written above can be reduced as below:
let event = arr.filter(item => item % 2 === 0)
Don’t worry, item can still recognize it as each item in arr so you can use that way.

Conclusion

Thus, you have learned about how to write reduced code when using Javascript Filter Function together with ES6. Remember to practice more and read more . This is the way to help you write code which is more logical, shorter and, of course, better.
And finally, don’t hesitate to comment below if you have any questions or additional ways you’ve used that work.
Share post
You must be logged in to post a comment
Top