Why is {} < function(){}?

2020-07-11 08:42发布

问题:

While I was messing around with truth tables in JavaScript, I noticed that the following evaluates to true:

var a, b, c;
a = {};
b = function(){};
c = a < b;
console.log(c);

Why?

I've only tested this in Firefox, and I'm sure I could dig up the details in the ECMAScript 2.6.2 spec, but TBH I'm feeling lazy.

回答1:

JavaScript type coercion makes the comparison essentially

String({}) < String(function(){})

so essentially you are just doing

"[object Object]" < "function (){}"

which is a lexicographic string comparison.



回答2:

Javascript compares objects by calling valueOf() or toString().
Since neither operand has a valueOf() method, it will compare the toString()s.

({}).toString() is [object Object].
(function() { }).toString() is function() { }.

[ is less than f.



回答3:

alert(({}))            -> [object Object]
alert((function(){}))  -> function () {}

[ comes before f, hence ({}) < (function () {}).

Yes, it's silly. ;)



回答4:

pretty simple and easy ( internally they are both converted to strings ) this is because in Javascript

If an object is compared with a number or string, JavaScript attempts to return the default value for the object. Operators attempt to convert the object to a primitive value, a String or Number value, using the valueOf and toString methods of the objects.

so when both are compared both objects are converted to string using the internal Tostring method

    a.toString()
"[object Object]"

b.toString()
"function () { }"

hence b will be greater than a ( larger string ) that's why b > a is true