Learn
Iterators
The .filter() Method
The .filter()
method in JavaScript is one of the most powerful and frequently used iterator methods. It creates a new array with all elements that pass the test implemented by the provided function.
Syntax
The syntax for the .filter() method is as follows:
Here, callback
is the function to test each element of the array. This function accepts between 1 and 3 arguments:
element
: The current element being processed in the array.index
(optional): The index of the current element being processed in the array.array
(optional): The array filter was called upon.
thisArg
(optional): Value to use as this
when executing callback.
Example
Here is a simple example of using the .filter()
method:
In this example, the .filter()
method creates a new array with words that have more than 6 characters.
Summary
To sum up, the .filter()
method is a powerful tool that allows you to create a new array from an existing one, including only those elements that meet certain criteria. It's a clean and efficient way to filter out what you need from an array.
Instructions
Declare a variable evenNumbers
and assign it the result of calling the .filter()
method on numbers
array. The element must be named number
.
Inside the .filter()
method, define a function that checks if a number is even.
Sign up to start coding
Already have an account?
Sign In