Type Comparison in Javascript

I saw in Crockford's Javascript book: The good parts that it makes typeof comparisons are as follows:

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

I made my own tests, and I think this is an β€œorder” of different types:

number <object or array <string <undefined

Is this how JS actually does a comparison?

+4
source share
2 answers

The typeof operator returns a string. A string is compared by its numerical value.

So, the comparison order < :

 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 type characters. The charCodeAt method returns a numeric charCode character in JavaScript.

I added an example of each type in the previous block. Most JavaScript developers are aware of the first types. The final xml type is less well known and can be obtained using typeof on EX4 .

typeof demo: http://jsfiddle.net/9G9zt/1/

+4
source

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

In principle, if one line begins with another, then this is the larger of the two, otherwise the first character position is compared, which differs from two.

See spec section 11.8.5

+1
source

Source: https://habr.com/ru/post/1387778/


All Articles