11

Can some tell me why the following code returns true in JavaScript?

console.log(true > null); //returns true
4
  • 14
    Yes because null is a falsy expression (then false) and comparison operator will convert it to a number (then true = 1 and false = 0). Commented Jul 23, 2012 at 14:41
  • 2
    @Adriano post it as answer is just that! Commented Jul 23, 2012 at 14:42
  • stackoverflow.com/questions/801032/null-object-in-javascript Commented Jul 23, 2012 at 14:42
  • @elclanrs I'm lazy to write a complete answer with references to JavaScript standard (for who is interested just start from section 11.8.2). Commented Jul 23, 2012 at 14:46

7 Answers 7

12

null is like false in this case, wich is 0 as a number. true is 1 as a number.

1 is bigger (>) than 0.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. I was wondering why is null === 0 false? Then I realised it needs to be coerced. So for those who need absolute proof, try + null === 0 which evaluates to true proving that indeed null is coerced to 0. Just thought this might help others.
7

They are converted to numbers, null gives 0 and true gives 1

http://ecma-international.org/ecma-262/5.1/#sec-11.8.5

If it is not the case that both Type(px) is String and Type(py) is String, then

  1. Let nx be the result of calling ToNumber(px). Because px and py are primitive values evaluation order is not important.
  2. Let ny be the result of calling ToNumber(py).
Number(null) //0
Number(true) //1

Comments

2

May be because true = 1 where null = 0

Comments

2

JavaScript does a lot of type coercion in the background and a lot of the results you'll find aren't useful (see http://wtfjs.com/).

In this case, true which is coerced as 1 is greater than null which is coerced to 0. Since 1 is greater than 0 the result is true.

If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.

From the MDN.

Comments

1

What's happening behind is that the relational operators ( > in this case) perform type coercion before doing the comparison. When doing the ToPrimitive, true gets coerced to a 1, and null to a 0. You can check details here of how the operators actually work here

Comments

0

The code is incorrect, you need to do:

console.log(true > typeof null);

Comments

0

The compare operator ">" forces both it's left and right side to be converted to numbers. Number(true) is 1, Number(null) is 0, so what is in the paranthesis is taken as "1>0", which is always true in result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.