Help understanding .filter() logic in functional programming

Tell us what’s happening:
I actually passed the challenge but I don’t understand the logic behind the .filter() that I used. My objective was to filter all array elements from arr that were empty spaces and apparently I did it, but I don’t know why, because I just declared a parameter cur and returned it. Any advice is appreciated, thanks!

Your code so far

// Only change code below this line
function urlSlug(title) {
let arr = title.toLowerCase().split(" ");
let space = arr.filter(function(cur){
return cur;
let str = space.join("-");
return str;
// Only change code above this line
urlSlug("Winter Is  Coming")

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0.

Challenge: Apply Functional Programming to Convert Strings to URL Slugs

Link to the challenge:

.filter() does nothing here, .split() removes the empty spaces and turns the string into an array. Then with .join() you returned the array to a string with dashes between arrays elements

I think .filter it is doing something, because if I comment it out I don’t pass this test:

urlSlug(" Winter Is Coming")

Filter will return the elements that the callback function was able to coerce to true.

In this case your filter callback is telling: “keep everything that can be coerced to true”.

so for example:

[true, false, 1, "aaa", "", 0].filter(val => val)
// [true, 1, "aaa"]

Hope it helps :sparkles:

1 Like

Yes because “” returns false so it filters it out.

further reading:

1 Like