Functional Programming: Apply Functional Programming to Convert Strings to URL Slugs -- solution

In the first solution for this challenge, below, what is the purpose of this part: filter((obj)=>{ return obj !==''; })?

var globalTitle = "Winter Is Coming";

// Add your code below this line
function urlSlug(title) {
return title.split(/\W/).filter((obj)=>{
    return obj !=='';
// Add your code above this line

var winterComing = urlSlug(globalTitle); // Should be "winter-is-coming"

The title.split(/\W/) returns an array of word strings and empty strings.

The filter part might be easier to understand if it was written as:

.filter((str) => {
    return str !=='';

The above will return a new array by iterating through array of words created by the split method and only keep the non-empty strings.


That’s so crazy.,… I never knew you could pass regex into .split(). Haha. Thnx @RandellDawson


.filter((str) => {
    return str;


.filter(str => str);

Works too. Since '' is false.

1 Like

Also-- /\W/ is quite a range. I would think it’s better to list specific characters with /[LITERAL_CHARACTERS_INSIDE_HERE]/

Do you know the term for what’s going on in your example (a boolean value being returned for what’s in the return statement, when you’re not explicitly saying return true/false)? …Type coercion?

All strings are true.

Empty strings are false.

In fact all of these result to false:

.filter() only returns true values… You can test any value with:

Boolean('example_str'); // true
Boolean(''); // false
1 Like

The answer to your question,.

.filter()'s return value is effectively doing Boolean(return_value)., so yes,. type coercion is what’s happening to the return value if it’s not already a boolean.

1 Like

One other example you may see as you program more is the !!

!!3 // true
!!’’ // false

It’s shorthand for type coercion to boolean.

The first ! converts it to a boolean (if it’s not already one) and inverses its value., the 2nd ! inverses its value again.

1 Like

Interesting, hadn’t heard of !!.
Thanks for the clarification!