3

I am trying to make some conditional statements while trying to solve a coding challenge. I have kept track of all the occurrences of letters of two strings in different objects. When I try to compare them by their counts if the count is undefined in the other object it evaluates to false even though the first value is truthy.

However;

1 > Boolean(undefined) evaluates to true. However 1 > undefined evaluates to false. Is there reason why the behavior is so ?

Ozan
  • 1,623
  • 3
  • 13
  • 25
  • Why don't you console log `Boolean(undefined)`? – trincot Oct 20 '18 at 18:42
  • @trincot It evaluates to false. In that case 1 > Boolean(undefined) evaluates to true. – Ozan Oct 20 '18 at 18:43
  • And that surprises you? In many programming languages false is considered as 0 when compared with numbers. – trincot Oct 20 '18 at 18:46
  • It surprises me that 1 > undefined evaluates to false. – Ozan Oct 20 '18 at 18:48
  • If your question is about `1 > undefined` why do you state it as `1 > Boolean(undefined)`? – trincot Oct 20 '18 at 18:49
  • The title of the question does state that. I wanted to make a comparison of both cases to know why the behavior differs. If you think this can be improved to clarify the question please kindly edit the post. – Ozan Oct 20 '18 at 18:51

2 Answers2

2

In order to use the comparison operator >, both operands must be numeric. 1 already is, so Boolean(undefined) (which evaluates to false by the way) must be converted to a number. When it is, you get 0.

// First, convert undefined to a Boolean
let bool = Boolean(undefined)
console.log(bool);

// Then convert that to a number
let num = Number(bool);
console.log(num);

So, 1 > 0 is true.

Things to understand:

JavaScript is a "loosely" or "weakly" typed language. This means that data can, and often is, implicitly converted (coerced) into a different type category.

All data can be classified as "truthy" or "falsy", which means that if converted to a Boolean, would it convert to true or false. Things like null, undefined, "", 0, false, and NaN are all "falsy". And false in JavaScript (and most other languages) converts to the number 0, while true usually converts to 1.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
2

Javascript does a lot of funky casting when you compare things together that usually shouldn't be comparable.

1>undefined casts undefined to a NaN, and you can't compare a number to a Not a Number so any comparison will return false >,<,== etc

When you do 1>Boolean(undefined) undefined is cast to its boolean equivalent false, then when it's compared it will be cast to a 0, you can confirm this by doing Number(Boolean(undefined)) and since 1 is bigger than 0 it returns true.

bug56
  • 189
  • 1
  • 8