getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

IsLessThan wrong output

paimfp opened this issue · comments

I already searched for this issue.

Edition: 2nd

Book Title: types-grammar

Chapter: ch4.md

Section Title: Relational Comparison

Problem:

In the second example we have:

IsLessThan(1,2, /*LeftFirst=*/ true );            // true

// equivalent of a fictional "IsGreaterThan()"
IsLessThan(2,1, /*LeftFirst=*/ false );          // false

in the second expression, the order of arguments were changed and LeftFirst is false.

If I understood it correctly, that basically means IsGreaterThan(2, 1). And 2 is greater than 1, it should be true not false.

Another options would be like so (Change just the LeftFirst argument):

IsLessThan(1,2, /*LeftFirst=*/ false ); // false

The example in the book is correct... here's why:

  • The fictional isGreaterThan(..) illustration would be for an expression in code like 1 > 2 -- which is obviously false -- so if it existed it would be called as isGreaterThan(1,2, ..), not isGreaterThan(2,1) as you supposed.

  • Since it's fictional, it's instead processed by JS as if the expression in code had been 2 < 1, thus using the isLessThan(..) function with the arguments reversed (isLessThan(2,1, ..))-- which again is clearly false.

  • The LeftFirst doesn't affect the semantics in terms of which argument is treated as less-than or greater-than, here... it controls only which of the two operand values would be computed first; this is in case either computation produced observable side-effects, and it needed to preserve expected "left to right" semantics of JS.

It's important to note that this is all meta (illustrative, not prescriptive) since these abstract operations don't actually exist as real functions to call; moreover, passing a boolean argument to a function as shown wouldn't actually have controlled the order of computation for the other previous arguments being passed.