Apply Functional Programming to Convert Strings to URL Slugs - doesn't work when I separate the code

Tell us what’s happening:
the hidden code passed the test. But when I wrote the functions separately like the following:

let temp = title.toLowerCase().split(/\W+/);
temp.filter(x => x != “”);
temp.join("-");
return temp;

It does not pass the test and won’t show the result when I test it with conosle.log. I wonder why. Isn’t it the same as the hidden code?

Your code so far


// the global variable
var globalTitle = "Winter Is Coming";

// Add your code below this line
function urlSlug(title) {
  let temp = title.toLowerCase().split(/\W+/).filter(x => x != "").join("-");
  return temp;  
}
// Add your code above this line

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

console.log(winterComing);

console.log(urlSlug(" Winter iS   Coming"))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/apply-functional-programming-to-convert-strings-to-url-slugs

This is not the same code, it does something different. filter creates a new array, it doesn’t modify temp. And join creates a new string, it doesn’t modify temp. So you are lowercasing the title, splitting it, then returning that.

Ah! I see. Because they are all pure functions and won’t mutate the original variable. So if I really need to separate the functions I’ll have to create new variable for the filter and join functions, right? Thank You!!

Yes, but it’s not to really do with purity, though yes, they do not mutate:

Step by step, if title is 'Winter Is Coming':

let temp = title.toLowerCase().split(/\W+/).filter(x => x != “”).join("-");

let temp = 'Winter Is Coming'.toLowerCase().split(/\W+/).filter(x => x != “”).join("-");

let temp = 'winter is coming'.split(/\W+/).filter(x => x != “”).join("-");

let temp = ['winter', 'is', 'coming'].filter(x => x != “”).join("-");

let temp = ['winter', 'is', 'coming'].join("-");

let temp = 'winter-is-coming';

In comparison:

let temp = title.toLowerCase().split(/\W+/);
temp.filter(x => x != “”);
temp.join("-");

let temp = 'Winter Is Coming'.toLowerCase().split(/\W+/);
temp.filter(x => x != “”);
temp.join("-");

let temp = 'winter is coming'.split(/\W+/);
temp.filter(x => x != “”);
temp.join("-");

let temp = ['winter', 'is', 'coming'];
temp.filter(x => x != “”);
temp.join("-");

let temp = ['winter', 'is', 'coming'];
// this happens, but you don't do anything with it, so discard it:
['winter', 'is', 'coming']
temp.join("-");

let temp = ['winter', 'is', 'coming'];
// this happens, but you don't do anything with it, so discard it
'winter-is-coming'

let temp = ['winter', 'is', 'coming'];
1 Like