FAQ: Iterators - The .filter() Method

const randomNumbers = [375, 200, 3.14, 7, 13, 852];

// Call .filter() on randomNumbers below
const smallNumbers = randomNumbers.filter(num => {
  return num < 250;
})

const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric', 'serene'];


// Call .filter() on favoriteWords below

const longFavoriteWords = favoriteWords.filter(word => {
  return word.length > 7;
})

This is the given solution for this exercise. However, shouldn’t this section of the code

const longFavoriteWords = favoriteWords.filter(word => {
  return word.length > 7;

read this instead?

const longFavoriteWords = favoriteWords.filter(longFavoriteWords => {
  return favoriteWords.length > 7;

Hello, @thegreysmith.

No. The solution code syntax is correct. Let’s break it down.
const longFavoriteWords = We are assigning a value to a newly declared variable with the const keyword.

favoriteWords.filter() The value to be assigned to longFavoriteWords will be the words ‘filtered’ out of the favoriteWords array.

filter(word => { return word.length > 7;}) Inside the parenthesis, word is the placeholder variable that will be assigned each element of the favoriteWords array one at a time in turn. If word.length > 7 evaluates to true the word will be returned. If it evaluates to false the word will not be returned. The returned words become elements of a new array that is returned by the .filter() method. This new array is the value assigned to longFavoriteWords.

1 Like

Hi, I don’t get why sometimes there is ‘return’ and sometimes there isn’t!
In the example it’s some strings in an Array, ‘return’ is written and in the exercice 2. another Array of strings and no need for return.
Please enlight me,
Best

It’s a matter of which syntax is deployed. Arrow functions with only a single statement or expression in the body do not need explicit return and may forego the curly braces.

a_add_b = (a, b) => a + b;

Note that it is all on one line. The implicit return value is the sum of a and b.

When curly braces are used, the return must be explicit.

a_add_b = (a, b) => {
    return a + b;
}
3 Likes

Hello, @miribel38.

In JavaScript all functions return something whether implicitly or explicitly. Typically, when we leave out the return keyword, our function will implicitly return undefined. Concise arrow body functions are an exception as @mtf has shown. A concise body arrow function will implicitly return the value rather than undefined as long as we don’t put curly braces around the body of the function. If we include the curly braces, and don’t explicitly use the return keyword, undefined will be returned.

const a_add_b1 = (a, b) => {a + b}
const a_add_b2 = (a, b) => {return a + b}
const a_add_b3 = (a, b) => a + b

console.log(a_add_b1(2, 2)) //undefined
console.log(a_add_b2(2, 2)) //4
console.log(a_add_b3(2, 2)) //4
4 Likes

I wonder if somone could me understand something:

const longFavoriteWords = favoriteWords.filter

( words => {

return words.length > 7

})

This returns words more than 7 letters but I was curious and removed the > 7 as I wanted to see if this would return the length of the words instead but it doesn’t. It gives me all the words from the array.

The callback of the filter method is a predicate function that only returns values that meet with the specified condition. words.length will be a number greater than zero, hence it is truthy, so the word is returned.

Hey, so when I console log it, it gives me all the words back and not the ones greater than 7. any ideas?

cheers

Welcome, @giga8739571630,

Please post your code so we can check it…

I’m having trouble with this as well. I still don’t understand why we have to use num. Is that something that’s specific to .filter ? This is super confusing and not acknowledged in the lesson.

What are the rules for using a variable like num or word vs coming up with a variable?
What are the rules for referencing the variable assigned to the array in the code block vs using something like num or word?
Are there more variables like num and word I should make note of or is this all?
Before I used word in the second task I got an error. Will that happen all the time or does it just apply now because the lesson checker is so specific?

If these methods are array specific why can’t it automatically take one piece of data at a time?

Thanks!

https://www.codecademy.com/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/learn-javascript-iterators/lessons/javascript-iterators/exercises/filter

Yes, all the variables in the universe. They are only labels. We get reserved and key words from the language, otherwise the sky is the limit.

`

I understand that part. That wasn’t my q. Im asking why it HAS to be word and num vs any other variable?

What are the rules for using a variable like num or word vs coming up with a variable?
What are the rules for referencing the variable assigned to the array in the code block vs using something like num or word?
Are there more variables like num and word I should make note of or is this all?
Before I used word in the second task I got an error. Will that happen all the time or does it just apply now because the lesson checker is so specific?

No rules, as such, only common sense guidelines. Think about the readers of your code (including yourself) and use variable names that best describe the object being referenced. If it is a number, then num is appropriate, then so is n or x or p, or price, tax and total.

word makes perfect sense if that is what is described.

words = sentence.split()
for (word of words) {

}

Note the singular/plural relationship. We have plenty of opportunities to implement this type of naming.

In many cases where the variable names are prescribed in the exercise those are the ones we should/must use so the lesson checker sees what is expected.

I’m having a hard time understanding where the num, word, etc are coming from. Are we declaring a new variable in every function?

Fore example -

const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric', 'serene'];
const longFavoriteWords = favoriteWords.filter(word => {return  word.length > 7;})

Where is ‘word’ coming from? Is it being declared in the function or is it built into the syntax?

Yes, it is the local parameter of the callback function. filter iterates over the context array (favoriteWords) and uses that parameter to identify each value, in turn.

Your example can be written in the relaxed syntax form…

favoriteWords.filter(word => word.length > 7)

The callback is a predicate function that returns a boolean. Only when the return is true does the word get appended to the output array.

I didn’t have any problem with this exercise as I understood and get the logic straight away but can I just comment that the part where it said “word” really confused me… (see screenshot)

where’s the connection for the " parameter, word" in this example? Because the array was assigned to “const words” :face_with_raised_eyebrow:

Hello, @blog2245393326.

word is simply a placeholder for each element of the words array. Each iteration of .filter() passes an element of the words array into the callback function assigning it to the parameter word. Then return word.length < 6 returns either true or false. When true is returned, the value assigned to word is added to the array shortWords.

The following would be equivalent where we define a named function rather than using an anonymous function as the callback:

const words = ["chair", "music", "pillow", "brick", "pen", "door"];

const findShortWords = word => word.length < 6;

const shortWords = words.filter(findShortWords);

Could also be written like:

function findShortWords(word) {
   return word.length < 6;
}

const shortWords = words.filter(findShortWords);

//or this is how I would normally write it:
const shortWords = words.filter(word => word.length < 6); //concise body arrow function

In any of the functions above the parameter word could be any legal name. word makes sense because we are passing each element of an array named words, but this would also work:

const shortWords = words.filter(albatross => albatross.length < 6);

The odd name seems out of place, but is inconsequential. Since we don’t really care what the name is, we could also use this:

const shortWords = words.filter(_ => _.length < 6);
1 Like

but if we just use “words” to replace “word” in that example, that would be ok too, right?

Well, it would work, but is bad practice because it creates confusion using the same same for both the array, and each element of the array passed to the callback function.

Ok I get it, you can use any name, it’s just to represent the parameter for the action. So in good practice as usual, always write the code as clean, clear and relating to the main focus as much as you can

1 Like