skip to Main Content

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);

This are the tests:

booWho(true) should return true.
Waiting:booWho(false) should return true.
Waiting:booWho([1, 2, 3]) should return false.
Waiting:booWho([].slice) should return false.
Waiting:booWho({ "a": 1 }) should return false.
Waiting:booWho(1) should return false.
Waiting:booWho(NaN) should return false.
Waiting:booWho("a") should return false.
Waiting:booWho("true") should return false.
Waiting:booWho("false") should return false.

My tries:

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

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

this two gives me a problem with this test: booWho(1) should return false

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


this one gives me a problem with this test: booWho(false) should return true.

I ended up passing with typeof, but i have no idea why the others are giving errors, thanks in advanced

3

Answers


  1. Use strict equality to prevent type coercion and separate the checks to true and false:

    function booWho(bool) {
      return bool === true || bool === false;
    }
    
    Login or Signup to reply.
  2. Your last try is close but you need to check for strict equality using a triple equal (===) because non-boolean values can be truthy or falsy as well. === prevents implicit conversion.

    function booWho(bool) {
      return bool === true || bool === false;
    }
    
    console.log(booWho(true));
    console.log(booWho(false));
    console.log(booWho(null));
    console.log(booWho([]));
    console.log(booWho({}));
    console.log(booWho(() => void 0));
    Login or Signup to reply.
  3. A slightly more compact version:

    function booWho(bool) {
      return !!bool === bool
    }
    

    You’re checking if coercing bool to a boolean will be of the same value and data type as the original bool value.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search