Follow

Follow

# Falsy Bouncer - JavaScript Solution & Walkthrough

## (13/16) Learn how to solve coding challenges using FreeCodeCamp's curriculum.

Benjamin Semah
·Apr 13, 2022·

• 13/16 Falsy Bouncer
• Understanding the Challenge
• Pseudocode
• Solving the Challenge
• Final Solution
• Congratulations!

## 13/16 Falsy Bouncer

Remove all falsy values from an array.

Falsy values in JavaScript are false, null, 0, "", undefined, and NaN.

Hint: Try converting each value to a Boolean.

``````function bouncer(arr) {

return arr;
}

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

Credit: FreeCodeCamp.org

## Understanding the Challenge

The Falsy Bouncer challenge requires that you complete the bouncer function. This bouncer function takes an array as `arr` as arguments.

Your task is remove all elements in `arr` that are falsy values. The challenge description provides a list of falsy values in JavaScript. They includes `false`, `null`, `0`, `" "`, `undefines`, `NaN`. This means that if any of these values is found in the given array, it should be removed.

We're also given a hint to try converting each value to a boolean.

## Pseudocode

``````Given an array of value
Loop through the array
For each iteration of the loop
convert value to a boolean
if boolean of value is false
remove the value from the array
return the finalArray
``````

## Solving the Challenge

We can use the `.filter()` method to solve this challenge. The `.filter()` returns all elements in an array that fulfils a conditon.

In this condition will be to check whether the boolean value of an element is true or false. If it is false, we'll ignore it. If it is true, we'll return it as part of the `finalArray`.

``````  let finalArray = arr.filter(data => {
if (Boolean(data)) {
return data
}
})
``````

At the end of the filtering, the `finalArray` will be made up of only elements that have truthy values. In other words all the falsy values will no longer exists in the array. We can then return finalArray and our function is complete.

``````return finalArray;
``````

## Final Solution

``````function bouncer(arr) {
let finalArray = arr.filter(data => {
if (Boolean(data)) {
return data
}
})
return finalArray;
}

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

## Congratulations!

You just cracked the 13th challenge in this series.

Cheers and happy coding!