Let’s Look at Some Javascript Methods
Let’s take a surface-level dive into some Javascript methods. “But Aubrie what is a method?” Well, let me tell you methods are a set of instructions applied to an object. Today we are going to take a look at the ones I have learned so far, filter(), find(), map(), reduce().
Before we dive into each method we have to create an array. If you want to follow along in your text editor, it’ll help you better understand how these methods work. Before we start every method needs a function placed immediately after the method with a callback to get our answer.
Alright, let’s begin with the filter method. A filter() will create a new array that passes any test we provide by the function. We are going to use simple tests to help you understand. Let’s filter through this array and return anyone that has a height over 60 inches, then console.log it out for our answer.
What do you think the answer will be?
Bam, and there we have it. We filtered through the array and found that Jennifer and Beth are the only two with a height of over 60 inches.
Now let’s move on to the find() method. Find() will, you guessed it find the first element in an array that passes our given test. Today let’s find() one of our people whose sign is libra. To do this we must create a function first, a function is a block of code designed to perform a certain task, then we can sort through and see if we get a true or false.
Let’s console.log this out, do you think we will get an answer?
Ta-da and there we have it, we received a true.
Onward and upward, let’s look at the map() method. Map() will create a new array after looping through and doing something with each element. Let’s say “Hi” to everyone.
Hello ladies!!
Let’s keep this rolling onto the last method. Reduce() is all about math, we take two parameters do some math, and return a single value. It does this by using the callback of an accumulator and current value. The accumulator will keep track of the total as we loop through the array. The current value is the parameter moving onto each element of the array, the actual item in the array. We are going to console.log the average age of the girls.
Let me explain the math we are performing.
What do you think the average age of the girls will be?
And there we have it, the average age of the ladies is 34.8 years.
I hope you have gained some understanding of the first four methods I’m learning. I know writing this has helped me, has it helped you?
Check back for more coding tutorials! 🤙🏻👋🏻 Until next time.