Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare types in Javascript

I saw in Crockford's Book Javascript: The Good Parts that he does typeof comparison like this:

return typeof a < typeof b ? -1 : 1;

I made my own tests and I think this is the "ordering" of the different types:

function < number < object or array < string < undefined

Is this how JS actually does the comparison?

like image 391
pedro Avatar asked Dec 23 '11 17:12

pedro


2 Answers

The typeof operator returns a string. String are compared by its numeric value.

So, the < comparison order would be:

type       charCode ("tfnosux".charCodeAt(i))   Example
boolean     98                                   true
function   102                                   Date
number     110                                   123
object     111                                   []
string     115                                   ""
undefined  117                                   undefined
xml        120                                   <x></x>

tfnosux are the first characters of the types. The charCodeAt method returns the numeric charCode of a character in JavaScript.

I have added an example of each type at the previous block. Most JavaScript developers know about the first types. The final type, xml, is less commonly known, and can be obtained by using typeof on EX4.

Demo of typeof: http://jsfiddle.net/9G9zt/1/

like image 61
Rob W Avatar answered Oct 09 '22 02:10

Rob W


It is not importance. typeof returns a string, and the comparison operators work for strings, by performing a "a simple lexicographic ordering on sequences of code point value values".

Basically, if one string starts with the other, then that is the greater of the two, otherwise the first character position that differs between the two is compared.

See section 11.8.5 of the spec

like image 35
Paul Butcher Avatar answered Oct 09 '22 00:10

Paul Butcher