Boo who - JavaScript Solution & Walkthrough

Boo who - JavaScript Solution & Walkthrough

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

10/16 Boo who

Check if a value is classified as a boolean primitive. Return true or false.

Boolean primitives are true and false.

function booWho(bool) {

  return bool;
}

booWho(null);

Credit: FreeCodeCamp.org

Understanding the Challenge

We are given a value bool. What we need to do to complete the function is to check whether the value is either true or false. If it is, then we return true. If it is not, then we return false.

This can be a bit tricky.

Note: If the value bool is true, the function should return true. And if the value bool is false, the function should return true. This is because true is a boolean primitive and false is also a boolean primitive.

Pseudocode

Given a value (bool)
  Check whether it is true or false
  if it is, return true
  if not, return false

Solving the Challenge

As always, there are a number of ways to go about this challenge. For this one, we will use the tenary operator.

The tenary operator works like this

condition ? code to execute if true : code to execute if false

First, you state a condition, followed by the question mark ?, then you state the code to be run or returned if the condition is met. This is followed by the : and then you state the code to be run or returned if the condition is not met.

So in the case of this challenge, using the tenary operator will look like this

(bool === true || bool === false) ? true : false;

First we check if the provided value bool is true or false. If it is, we return true. if not, we return false.

Our function is now complete!

Final Solution

function booWho(bool) {
  return (bool === true || bool === false) ? true : false;
}

booWho(null); // false

Congratulations!

You just cracked the ninth challenge in this series.

Cheers and happy coding!