Why Is "1" equal to the value of a boolean in JS?

Tell us what’s happening:

I was doing the “Boo Who” challenge and wrote in the return statement to return true if the function input was “true” or “false”. I did it and passed all of the tests except one (booWho(1) should return false).
I logged booWho(1) to the console to see what value was returned and the JS console outputted “true”.
Can you please explain why this happens?
Do I have a mistake in my code?

Thanks.

Your code so far


function booWho(bool) {
// What is the new fad diet for ghost developers? The Boolean.
return bool == true || bool == false;
}

console.log(booWho(1));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36.

Challenge: Boo who

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/boo-who

1 Like

Do you know what the difference between == and === is? I think your problem lies there.

3 Likes

Also, is there a more general way you can code this to do this same test for integers? You can’t test against all possible integers.

Thanks. That was my mistake. Solved.

1 Like
function booWho(bool) {
// What is the new fad diet for ghost developers? The Boolean.
return bool == true || bool == false;    // use "===" not "==". 
}

console.log(booWho(1));

The ( == ) equality operator can get one into trouble. It will convert the
operands to the same data type if they are not of the same type BEFORE making a comparison. It tests only for type. I would recommend reading about ‘coercion’.

The ( === ) strict equality operator result in true if both operands are of
the same data type and the values match. It depends on the code design if choosing to use one or the other.

2 Likes