2

I am comparing the value null to a string. However the result of the comparison is always false.

null > "a" // false

null < "a" // false

"a" > null // false

"a" > null // false

Can anyone explain why this is happening?

I did find a section (http://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5) within the ECMAScript standard that seems to explain what is going on, but I do not really understand what the standard says.

5
  • 4
    Where's that question on SO with 1000 upvotes that talked about string comparison in javascript? Anybody? Commented Mar 25, 2014 at 16:55
  • I think this post answers your question: stackoverflow.com/questions/13407544/… Commented Mar 25, 2014 at 16:56
  • What do you expect the result to be? Commented Mar 25, 2014 at 17:06
  • @DeanMeehan It does. And before I asked the question I also searched SO for an answer. But the question that was linked above, was talking about numbers copared to null and not strings. That is why I could not find it even though the answer to both questions is similar. Commented Mar 25, 2014 at 17:19
  • And this matters because...? Commented Mar 25, 2014 at 17:21

2 Answers 2

2

11.8.5 is the abstract relational expression, the production relational expression is what you need to look at, which includes the abstract one.

11.8.1 The Less-than Operator ( < ) // pretty much the same as >

The production RelationalExpression : RelationalExpression < ShiftExpression is evaluated as follows:

    1) Let lref be the result of evaluating RelationalExpression.
    2) Let lval be GetValue(lref).
    3) Let rref be the result of evaluating ShiftExpression.
    4) Let rval be GetValue(rref).
--> 5) Let r be the result of performing abstract relational comparison 
       lval < rval. (see 11.8.5)
--> 6) If r is undefined, return false. Otherwise, return r.

When you look at the abstract relation comparison, the result will be undefined because Number('a') => NaN (Rule 3) which will set off these rules: If nx is NaN, return undefined or If ny is NaN, return undefined.

So 6) Let r be the result of performing abstract relational comparison, in your cases r is then undefined. The last step says if r is undefined then return false, hence your answer.

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

Comments

0

Both section 3 and 4 of the reference say "return false" if nothing else is true.

There simply aren't any other options given the spec you've quoted.

Not that having it be either greater or less than would make any sense anyway.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.