Url slug works, don't know why [Spoiler]

I wrote the following code to solve the url slug challenge, and I’m not positive on why it works.

function urlSlug(title) {
    var lowerCharArr = title.toLowerCase().split(" ");
    return lowerCharArr.filter((word) => {
        return word;
    }).join("-");
  
}

I can see that the split on line 2 creates empty arrays but I’m not sure why my filter() method discards those from the return.

I ended up writing the following code for clarity…

function urlSlug(title) {
    var lowerCharArr = title.toLowerCase().split(" ");
    return lowerCharArr.filter((word) => {
        return word != '';
    }).join("-");
  
}

My friend earlier explained it as something to do with the way js handles typecasting but if someone could explain further that would be great! Thanks everyone :slight_smile:

Empty strings are evaluated as false so your first filter function is discarding empty strings.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.