Bonfire: Falsy Bouncer Solution

Having checked the Bonfires recently to this post for the Falsy Bouncer Bonfire, I discovered Free Code Camp has included a new Bonfire for the Beginner’s Algorithm Scripting challenges. I haven’t looked at it yet, but it sounds intriguing as a Caesar’s Cipher involves moving letters a certain number of spaces and can appear in a number of skill tests. Anyway, we’re dealing with the Falsy Bouncer in this post, so here’s what the Bonfire gives us to work with:

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
  return arr;
}

bouncer([7, "ate", "", false, 9]);

Bonfire wants us to remove all the false values in the array. Within Javascript’s lexicon, false is equivalent to: false, NaN, undefined, 0, null and “”. Given what we have above, I’m assuming they want us to exclude “” and the false value so that 7 will eat 9. Let’s get this show on the road.

Approaching the Problem

  1. I already know in Javascript what it considers as a false value already, so I need a way for an if statement to exclude those values before returning the array in bouncer() without them.
  2. The Bonfire gives us a hint about what we can use by suggesting we look into the filter() method.
  3. If we just filter out the false values, we can easily return the non-false values in the array and validate our solution.

It would seem that our path is pretty clear cut on this one. So let’s dive into it and look at what filter() does.

Looking at Filter()

Filter is a method added to ECMAScript (Javascript) 5. It allows Javascript to arrays to test values in an array for true and returns a new array by filtering out those values that didn’t pass the test. It’s a handy new feature and I can understand why the Falsy Bouncer Bonfire can be solved in this way.

The crazy thing about filter() is that it takes in a function and an object as arguments. So a typical filter() method’s syntax looks like this: filter(callback[, thisArg]). Callback is the function that you use to test the values in an array, element or index. thisArg is an object you may or may not use as a form of this, it is considered optional.

That might sound like a lot of Martian up there so here’s an example of filter() in use, where we invoke filter() to weed out and return only the strings in an array:

var mishMash = [4, "cookies", true, "cake", 18, "peppermints", 0];

var isTreat = mishMash.filter(
    function (treat) {
        return (typeof treat === "string");
    }
);
console.log(isTreat);

In the above section of code, we first create an array called mishMash. Inside of mishMash, we have a mixture of values. Some numbers, some strings and a true boolean value. What I want to do is create another array that contains only strings.

What we create on the next line is a new array called isTreat. isTreat is populated using the filter() method on mishMash. Inside filter() we feed it a function that takes in a property of “treat”. treat, inside of the function, is tested to see if it is a string or not. If it is a string, it gets returned. Once treat gets returned it is added to isTreat as a value of the array. And finally, we log out isTreat which should tell us that its array’s values are “cookies, cake, peppermints”.

Here’s another example, where we check for true values inside of an array. By default, in Javascript, true is any value that isn’t false. So, as long as it doesn’t return as false, 0, null, NaN, undefined or an empty string, it will return in our array:

var lies = ["cake", 5, true, 0, 1, true, "", false];

var nothingBut = lies.filter(
    function (theTruth) {
        return theTruth;
    }
);
console.log(nothingBut);

In the above code, we’re looking for, theTruth, or any value that isn’t false which means the array should exclude 0, “” and false. What we do is start a new array called nothingBut. We feed nothingBut the lies array, using the filter() method. Filter takes in a function that checks for true, it refers to true as theTruth.

Remember that the filter() method tests values in an array, element or index for true by default, so we don’t have to do anything for filter except have it return the values to the new nothingBut array. The result when you log it out is “cake”, 5, true, 1, true. Therefore, successfully excluded all false values and only gave us the truth, and nothing but the truth.

Chatting Briefly About typeof

You probably noticed typeof being used up there as a way to evaluate whether something is a string or not. I feel like it’s necessary to mention typeof because I haven’t used it before and therefore, haven’t explained myself yet. So in the interest of being thorough, let’s take a brief look at typeof.

Typeof is a Javascript operator. It’s used to evaluate and return the type of something. As you can see above, typeof is very useful for evaluating if something is a string. You can also evaluate for numbers, nulls, undefines, booleans, objects, functions and more.

A typical use of typeof:

var cats = "felines";
console.log(typeof cats);

The above should log, “string”, because, well that’s what the variable cats is holding onto. Here’s another example:

var sharks = ["hammerhead", "mako", "great white"];
console.log(typeof sharks);

The above should log, “object”, which is true because an array is a type of object in Javascript. You can get more specific if you need to determine an array from another type of object by using the Array.isArray() method, but let’s not open that can of worms right now. Finally, a really simple last example:

var cake = false;
console.log(typeof cake);

The above logs a “boolean”. Now we know how typeof is used and you also know how much I love the Portal games.

Knowing how to filter out true values and being acquainted with typeof, we can now apply filter() to figure out our Falsy Bouncer Bonfire challenge.

The Falsy Bouncer Solution

So, filter() checks for true values. Seeing as we’re 99% of the way there in our filter() example above, let’s just apply the same thing to our Bonfire to get our solution:

function bouncer(arr) {
    var truths = arr.filter(function(filterTrue) {
        return filterTrue;
    });
    return truths;
}

bouncer([7, "ate", "", false, 9]);

In the code above, we declare the bouncer() function with an array as an argument (arr). Inside of that function, we create a new array called truths. This array will hold only the true values returned by the filter() method. The new truths array is declared to have values of arr which are put through the filter() method. Filter() checks for and tests all array values for true and returns these values in the form of the filterTrue argument.
Finally, when all the values in the array are checked and the false ones are excluded by filter(), we return truths to bouncer() and get all our truths and none of the falses. Run this one through the Bonfire and it will validate! Looks like we just solved our Falsy Bouncer challenge.

Resources

Dive Into Javascript, Array Filter Page
A useful page describing filter() and how it’s used, including a bunch of examples for its usage.

MDN, Filter()
MDN’s explanation and examples for the filter() method.

MDN, Typeof
MDN’s page on the typeof operator, includes examples and explanations.


Posted

in

by

Comments

12 responses to “Bonfire: Falsy Bouncer Solution”

  1. Akindairo

    I just love your solutions, they are simple, clear and straight, good enough for beginners.

    1. Glad this was helpful, Akindairo. Thanks for leaving a message! 🙂

  2. So basically any argument could have gone in the internal function because no matter what you call it; filterTrue or noFalsys or whatever the filter just goes through the arr and returns only true values. It’s really pretty simple when you think about it. Again, your tutorials are fantastic. I feel like you’re talking to me.

    Mark

    1. Thank you for the nice comment, Mark. It makes me happy to know these posts are helping people who are learning Javascript. 😀

  3. Nick

    I really appreciate the clarity of your explanations. Thanks for doing this!

    1. My pleasure, Nick. Thank you for dropping by and leaving a comment!

  4. James

    Hi Khanh, you’re a lifesaver! I just have one question that’s somewhat related to the challenge at hand, it has more to do with the fact that this Bonfire challenge is one of the first to introduce more than 1 function to play around with. My difficult revolves around the fact that I’m not sure what is passed through as arguments for your filterTrue function – does it just check every argument passed through bouncer?

    i.e. for bouncer([7, “ate”, “”, false, 9]);
    the first argument through bouncer would be 7 – is the same 7 also then passed through filterTrue? If so, how does the syntax allow this (I would’ve thought you needed something like filterTrue(arr))? I hope this question makes sense, this has given me some grief in trying to understand the solutions for this challenge posted around.

    1. Hi James, the 7 is the same 7 that would pass through the filter method. The reason why filterTrue was put in as the argument for filter is because the filter method needed an argument to return up through the chain for truths. Since arr was already being told to run the filter method, it necessitated a different argument name. That’s my understanding of it anyway! 🙂

    2. Sohel

      I think your concern in related to the second line,
      function bouncer(arr) {
      var truths = arr.filter(function(filterTrue) {
      You see that in the second line filter method was called on the arr, which is the argument passed to the bouncer function. So whatever elements the arr arguments hold, filter method will be called on the value of each element one by one. And each of this value will be passed as the argument for the filter method, which is currently holding filterTrue as a parameter, given that this parameter is just simply a space holding name, which can be anything i.e. x, y, z ……
      Hope this made sense and answered your question. To get a better understanding of how filter method works you can check out this page MDN, Filter()

      1. Thanks so much, Sohel! 🙂

  5. Yanuar

    thanks for the tutorial its help me much. i just new learning javascript and still blind with it

    1. No problem, Yanuar. Thanks for leaving a comment. 🙂