Recall & Review
beginner
What does the
filter method do in JavaScript?The
filter method creates a new array with all elements that pass a test implemented by a provided function.Click to reveal answer
beginner
How do you use the
filter method syntax?You call
array.filter(callback(element, index, array)). The callback returns true to keep the element, or false to remove it.Click to reveal answer
beginner
What type of value must the callback function return when used with
filter?The callback must return a boolean value:
true to keep the element, false to exclude it from the new array.Click to reveal answer
beginner
Can the
filter method change the original array?No,
filter does not modify the original array. It returns a new array with the filtered elements.Click to reveal answer
beginner
Give a simple example of using
filter to get even numbers from an array.Example:<br><code>const numbers = [1, 2, 3, 4];<br>const evens = numbers.filter(n => n % 2 === 0);<br>console.log(evens); // [2, 4]</code>Click to reveal answer
What does the
filter method return?✗ Incorrect
The
filter method returns a new array containing only the elements that pass the test in the callback function.Which value should the callback function return to keep an element?
✗ Incorrect
Returning
true keeps the element in the new filtered array.Does
filter change the original array?✗ Incorrect
filter always returns a new array and does not modify the original.What will
[1, 2, 3].filter(n => n > 2) return?✗ Incorrect
Only the number 3 is greater than 2, so the new array contains [3].
Which of these is a valid use of
filter?✗ Incorrect
The callback must return a boolean.
element === 5 returns true or false, so it is valid.Explain how the
filter method works and what it returns.Think about how you pick items from a list based on a rule.
You got /4 concepts.
Write a simple example using
filter to select only strings longer than 3 characters from an array.Use <code>str.length > 3</code> inside the callback.
You got /4 concepts.